package com.xinchuang.service.targetSystem.Impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xinchuang.common.KeyWordSystem;
import com.xinchuang.common.Result;
import com.xinchuang.common.ResultEnum;
import com.xinchuang.common.ResultUtil;
import com.xinchuang.entity.repacigi.RepacigiMainTable;
import com.xinchuang.entity.repacigi.RepacigiSubTable;
import com.xinchuang.entity.target.TargetBaseData;
import com.xinchuang.entity.targetSystem.ExecutableState;
import com.xinchuang.entity.targetSystem.FontTable;
import com.xinchuang.entity.targetSystem.object.TargetPostureAdd;
import com.xinchuang.entity.targetSystem.object.TargetSubAdd;
import com.xinchuang.entity.targetSystem.target.*;
import com.xinchuang.mapper.targetSystem.*;
import com.xinchuang.entity.targetSystem.Zone;
import com.xinchuang.entity.targetSystem.config.TargetElse;
import com.xinchuang.entity.targetSystem.object.TargetAdd;
import com.xinchuang.entity.targetSystem.object.TargetFindData;
import com.xinchuang.entity.targetSystem.system.*;
import com.xinchuang.entity.targetSystem.weapon.WeaponMessage;
import com.xinchuang.entity.targetSystem.weapon.WeaponRelation;
import com.xinchuang.mapper.targetSystem.config.TargetElseMapper;
import com.xinchuang.mapper.targetSystem.target.SystemsRangeTypeMapper;
import com.xinchuang.mapper.targetSystem.weapon.WeaponHouseMapper;
import com.xinchuang.pojoUtil.TargetUtil;
import com.xinchuang.service.RedisUseService;
import com.xinchuang.service.repacigi.RepacigiMainTableService;
import com.xinchuang.service.repacigi.RepacigiSubTableService;
import com.xinchuang.service.target.TargetBaseDataService;
import com.xinchuang.service.targetSystem.*;
import com.xinchuang.service.targetSystem.config.SystemConfigService;
import com.xinchuang.service.targetSystem.external.ApiService;
import com.xinchuang.service.targetSystem.target.*;
import com.xinchuang.sqlite.entity.TargetData;
import com.xinchuang.util.*;
import com.xinchuang.utils.MyUtil;
import com.xinchuang.utils.RedisName;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.*;

/**
 * @ClassName TargetServiceImpl
 * @Description: 目标实现类
 * @auther zx
 * @data 2021/4/2  10:34
 * @Version V1.0
 */
@Slf4j
@Service(value = "targetService")
public class TargetServiceImpl implements TargetService {

    //雪花ID
    private SnowflakeIdWorker snow = new SnowflakeIdWorker(1, 1);

    @Resource
    private KeyWordSystem keyWordSystem;

    @Resource
    private TargetMapper targetMapper;

    @Resource
    private TargetTypeMapper targetTypeMapper;

    @Resource
    private TargetSubTypeMapper targetSubTypeMapper;

    @Resource
    private CommonMapper commonMapper;

    @Resource
    private TargetRelationMapper targetRelationMapper;

    @Resource
    private ZoneMapper zoneMapper;

    @Resource
    private SystemPositionMapper systemPositionMapper;

    @Resource
    private SystemRelationMapper systemRelationMapper;

    @Resource
    private SystemsRelationMapper systemsRelationMapper;

    @Resource
    private SystemsMasterMapper systemsMasterMapper;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private TargetMsgTableService targetMsgTableService;

    @Resource
    private TargetSubRelationTableService targetSubRelationTableService;

    @Resource
    private TargetSubMsgTableService targetSubMsgTableService;

    @Resource
    private TargetSystemRelationService targetSystemRelationService;

    @Resource
    private TargetPostureRelationTableService targetPostureRelationTableService;

    @Resource
    private TargetPostureMsgTableService targetPostureMsgTableService;

    @Resource
    private PostureAttributeService postureAttributeService;

    @Resource
    private PostureTypeService postureTypeService;

    @Resource
    private SystemIndexService systemIndexService;

    @Resource
    private SystemIndexElseService systemIndexElseService;

    @Resource
    private TargetBaseDataService targetBaseDataService;

    @Resource
    private RedisUseService redisUseService;

    @Resource
    private DeleteService deleteService;

    @Resource
    private ExecutableStateService executableStateService;

    @Resource
    private AsyncService asyncService;

    @Resource
    private SystemsRangeTypeMapper systemsRangeTypeMapper;

    @Resource
    private TargetRelationshipService targetRelationshipService;

    @Override
    @Transactional
    public Result<Map<String, Object>> addTarget(TargetAdd targetAdd, String userId) throws SQLException {
        String targetId = snow.nextId() + "";
        com.xinchuang.entity.targetSystem.target.TargetData targetData = new com.xinchuang.entity.targetSystem.target.TargetData();
        targetData.setTargetId(targetId);
        //获取目标的基础参数的封装
        List<TargetMsgTable> targetMsg = TargetUtil.getTargetMsg(targetData, targetId, targetAdd, userId, 1);
        //重命名判断
        if (juageTargetName(targetData.getTargetId(), targetData.getTargetName())) {
            return ResultUtil.error(ResultEnum.SYSTEMS_NAME_EXIST);
        }
        targetData.setIndexValue("0");
        targetData.setDeleteSign(1);
        //保存基础
        targetMapper.save(targetData);
        redisUseService.updateIsTarget(targetData.getTargetId());
        //属性保存
        targetMsgTableService.saveBatch(targetMsg);
        redisUseService.updateTargetBase(targetData.getTargetId(), targetMsg);
        //系统类型归类
        targetSystemRelationService.save(
                TargetSystemRelation.builder()
                        .targetId(targetId)
                        .targetClassify(targetData.getType())
                        .country(targetData.getCountry())
                        .build()
        );
        //目标作用范围
        targetRangeType(targetId, targetMsg);
        //构建指标值
        buildIndex(targetId, targetData.getType(), targetData.getTargetName());
//        RepacigiMainTable build = RepacigiMainTable.builder().tarId(targetId).tarName(targetData.getTargetName()).build();
//        repacigiMainTableService.saveOrUpdate(build);
        //返回值封装
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("targetId", targetId);
        return ResultUtil.success("新增基础信息成功", resultMap);
    }

    @Override
    public Result<Map<String, Object>> getList(TargetFindData targetFindData) {
        List<String> type;
        if (null == targetFindData.getClassify() || targetFindData.getClassify().isEmpty()) {
            targetFindData.setClassify(null);
        } else {
            type = targetMapper.selectTargetTypeNames(targetFindData.getClassify());
            if (CollectionUtil.isNotEmpty(type)) {
                targetFindData.setClassify(type);
            }
        }
        if (StringUtils.isBlank(targetFindData.getKeyword())) {
            targetFindData.setKeyword(null);
        }

//        PageHelper.startPage(targetFindData.getPageNum(), targetFindData.getPageSize());
//        List<com.xinchuang.entity.targetSystem.target.TargetData> list =
//                targetMapper.findAll(country, targetFindData.getClassify(), targetFindData.getKeyword());
//        PageInfo<com.xinchuang.entity.targetSystem.target.TargetData> pageInfo = new PageInfo<>(list);

        QueryWrapper<TargetBaseData> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(TargetBaseData::getDeleteSign, 1)
                .in(CollectionUtil.isNotEmpty(targetFindData.getCountry()), TargetBaseData::getCountry, targetFindData.getCountry())
                .in(CollectionUtil.isNotEmpty(targetFindData.getClassify()), TargetBaseData::getType, targetFindData.getClassify())
                .like(StringUtils.isNotBlank(targetFindData.getKeyword()), TargetBaseData::getTargetName, targetFindData.getKeyword())
                .orderByDesc(TargetBaseData::getCreateTime);

        Page<TargetBaseData> page = targetBaseDataService.page(new Page<>(targetFindData.getPageNum(), targetFindData.getPageSize()), wrapper);

        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> resultList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(page.getRecords())) {
            for (TargetBaseData targetData : page.getRecords()) {
                Map<String, Object> map = new HashMap<>();
                map.put("targetId", targetData.getTargetId());
                map.put("targetName", targetData.getTargetName());
                map.put("targetClassify", targetData.getTargetClassify());
                map.put("icon", StringUtils.isNotBlank(targetData.getIcon()) ? this.keyWordSystem.getSERVER_URL() + targetData.getIcon() : "");
                resultList.add(map);
            }
        }
        resultMap.put("targetList", resultList);
        resultMap.put("pageNum", page.getCurrent());
        resultMap.put("pageSize", page.getSize());
        resultMap.put("total", page.getTotal());
        resultMap.put("pageAll", page.getPages());
        return ResultUtil.success("查询成功", resultMap);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Result<Map<String, Object>> updateTarget(TargetAdd targetAdd, String userId) throws SQLException {
        com.xinchuang.entity.targetSystem.target.TargetData targetData = targetMapper.findTargetOnly(targetAdd.getTargetId());
        if (ObjectUtil.isEmpty(targetData) || targetData.getDeleteSign() == 0) {
            return ResultUtil.error(ResultEnum.TARGET_EMPTY);
        }
        String oldType = targetData.getType();
        List<TargetMsgTable> targetMsg = TargetUtil.getTargetMsg(targetData, targetAdd.getTargetId(), targetAdd, userId, 1);
        if (juageTargetName(targetData.getTargetId(), targetData.getTargetName())) {
            return ResultUtil.error(ResultEnum.SYSTEMS_NAME_EXIST);
        }
        //指标判断
        Integer count = systemIndexService.lambdaQuery().eq(SystemIndex::getRedId, targetData.getTargetId()).count();
        if (count == 0) {
            //构建指标值
            buildIndex(targetData.getTargetId(), targetData.getType(), targetData.getTargetName());
        } else {
            //判断类型修改指标重新计算
            if (!oldType.equals(targetData.getType())) {
                systemIndexService.lambdaUpdate().eq(SystemIndex::getRedId, targetAdd.getTargetId()).remove();
                //构建指标值
                buildIndex(targetData.getTargetId(), targetData.getType(), targetData.getTargetName());
            }
        }
        //系统所属类型判断变更
        targetSystemRelationService.saveOrUpdate(
                TargetSystemRelation.builder()
                        .targetId(targetAdd.getTargetId())
                        .targetClassify(targetData.getType())
                        .country(targetData.getCountry())
                        .build()
        );
        //修改指标主体名称
        systemIndexService.lambdaUpdate()
                .eq(SystemIndex::getRedId, targetData.getTargetId())
                .eq(SystemIndex::getParentId, "0")
                .set(SystemIndex::getIndicatorName, targetData.getTargetName())
                .update();
        targetMapper.update(targetData);
        if (CollectionUtil.isNotEmpty(targetMsg)) {
            //清理之前的数据
            targetMsgTableService.lambdaUpdate()
                    .eq(TargetMsgTable::getRedId, targetAdd.getTargetId())
                    .eq(TargetMsgTable::getMsgType, 1)
                    .remove();
            targetMsgTableService.saveBatch(targetMsg);
            redisUseService.updateTargetBase(targetData.getTargetId(), targetMsg);
            //目标作用范围
            targetRangeType(targetAdd.getTargetId(), targetMsg);
        }
//        RepacigiMainTable build = RepacigiMainTable.builder().tarId(targetAdd.getTargetId()).tarName(targetName).build();
//        repacigiMainTableService.saveOrUpdate(build);
        return ResultUtil.success("更新基础信息成功", null);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public synchronized Result<Map<String, Object>> deleteTarget(List<String> ids) {
        for (String id : ids) {
            TargetBaseData targetBaseData = targetBaseDataService.getById(id);
            if (ObjectUtil.isEmpty(targetBaseData)) {
                continue;
            }
            targetBaseDataService.lambdaUpdate()
                    .set(TargetBaseData::getDeleteSign, 0)
                    .eq(TargetBaseData::getTargetId, targetBaseData.getTargetId())
                    .update();
            //相关删除
            deleteService.deleteTarget(targetBaseData);
        }
        return ResultUtil.success("删除成功", null);
    }

    @Override
    public Result selectTarget(String targetId) throws SQLException {
        com.xinchuang.entity.targetSystem.target.TargetData targetData = targetMapper.findTargetOnly(targetId);
        if (ObjectUtil.isEmpty(targetData) || targetData.getDeleteSign() == 0) {
            return ResultUtil.error(ResultEnum.TARGET_EMPTY);
        }
        Map<String, Object> resultMap = new HashMap<>();
        List<CommonAttribute> commonAttributes = commonMapper.findCommons(1);
        TargetUtil.getCommonAttributesList(resultMap, commonAttributes);
        List<TargetMsgTable> msgTables = targetMsgTableService.lambdaQuery()
                .eq(TargetMsgTable::getRedId, targetId)
                .eq(TargetMsgTable::getMsgType, 1).list();
        if (CollectionUtil.isNotEmpty(msgTables)) {
            TargetUtil.getTargetMsg(resultMap, msgTables);
        }
        return ResultUtil.success("查询基础信息成功", resultMap);
    }

    @Override
    public Result selectTargetSpecial(String targetId) throws SQLException {
        com.xinchuang.entity.targetSystem.target.TargetData targetData = targetMapper.findTargetOnly(targetId);
        if (ObjectUtil.isEmpty(targetData) || targetData.getDeleteSign() == 0) {
            return ResultUtil.error(ResultEnum.TARGET_EMPTY);
        }
        Map<String, Object> special = new HashMap<>();
        List<SpecialAttribute> types = targetTypeMapper.findSpecialByTypeId(targetData.getTargetClassify());
        TargetUtil.getSpecialAttributesList(special, types);
        List<TargetMsgTable> msgTables = targetMsgTableService.lambdaQuery()
                .eq(TargetMsgTable::getRedId, targetId)
                .eq(TargetMsgTable::getMsgType, 2).list();
        if (CollectionUtil.isNotEmpty(msgTables)) {
            TargetUtil.getTargetMsg(special, msgTables);
        }
        return ResultUtil.success("查询成功", special);
    }

    /**
     * 新增/更新子目标
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Result<Map<String, Object>> addTargetSub(TargetSubAdd targetSubAdd, String userId) throws SQLException {
        com.xinchuang.entity.targetSystem.target.TargetData targetData = targetMapper.findTargetOnly(targetSubAdd.getTargetId());
        if (ObjectUtil.isEmpty(targetData) || targetData.getDeleteSign() == 0) {
            return ResultUtil.error(ResultEnum.TARGET_EMPTY);
        }
        String name = null;
        String classify = null;
        String oldType = "";
        for (TargetData data : targetSubAdd.getSubList()) {
            if ("targetName".equals(data.getKey())) {
                name = data.getKeyValue();
            } else if ("targetClassify".equals(data.getKey())) {
                classify = TargetUtil.getParamListOrString(data.getKeyValue());
            }
        }
        //判断类型是否存在
        if (ObjectUtil.isEmpty(targetSubTypeMapper.selectById(classify))) {
            return ResultUtil.error(ResultEnum.TARGET_SUB_TYPE_IS_ERROR);
        }
        String subId;
        if (StringUtils.isBlank(targetSubAdd.getSubId()) || targetSubAdd.getSubId().equals("0")) {
            subId = String.valueOf(snow.nextId());
        } else {
            subId = targetSubAdd.getSubId();
        }
        List<TargetSubMsgTable> msg = targetSubMsgTableService.getSubMsgByTargetIdAndKeyIdAndKeyValue(
                targetSubAdd.getTargetId(),
                subId,
                "targetName",
                name
        );
        if (CollectionUtil.isNotEmpty(msg)) {
            return ResultUtil.error(402, "子目标名称重复，请重新填写");
        }
        List<TargetSubMsgTable> subMsg = TargetUtil.getSubMsg(subId, targetSubAdd.getSubList(), userId, 1);
        //清理之前的数据
        if (redisUtil.hasKey(RedisName.TARGET_BASE_DATA_ALL + "_" + subId)) {
            oldType = TargetUtil.getObjectListOrString(redisUtil.hget(RedisName.TARGET_BASE_DATA_ALL + "_" + subId, "targetClassify"));
        }
        targetSubMsgTableService.lambdaUpdate()
                .eq(TargetSubMsgTable::getSubId, subId)
                .ne(TargetSubMsgTable::getKeyId, "icon")
                .eq(TargetSubMsgTable::getMsgType, 1)
                .remove();
        if (CollectionUtil.isNotEmpty(subMsg)) {
            //修改指标主体名称
            systemIndexService.lambdaUpdate()
                    .eq(SystemIndex::getRedId, subId)
                    .eq(SystemIndex::getParentId, "0")
                    .set(SystemIndex::getIndicatorName, name)
                    .update();
            //更新子目标基础信息
            targetSubMsgTableService.saveBatch(subMsg);
            redisUseService.updateSubBase(subId, subMsg);
            //子目标作用范围
            subRangeType(subId, subMsg);
        }
        //指标判断
        Integer count = systemIndexService.lambdaQuery().eq(SystemIndex::getRedId, subId).count();
        if (count == 0) {
            //构建指标值
            buildIndex(subId, classify, name);
        } else {
            //判断类型修改指标重新计算
            if (!oldType.equals(classify)) {
                systemIndexService.lambdaUpdate().eq(SystemIndex::getRedId, subId).remove();
                //构建指标值
                buildIndex(subId, classify, name);
            }
        }
        //创建子目标关联
        TargetSubRelationTable relationTable = null;
        if (StringUtils.isBlank(targetSubAdd.getSubId()) || targetSubAdd.getSubId().equals("0")) {
            relationTable = new TargetSubRelationTable();
            relationTable.setTargetId(targetSubAdd.getTargetId());
            relationTable.setSubId(subId);
            relationTable.setPreType(1);
            //更新目标与子目标关联
            targetSubRelationTableService.save(relationTable);
            redisUseService.updateTargetSubRelation(true, targetData.getTargetId(), subId);
            redisUseService.updateIsSub(subId);
        } else {
            relationTable = targetSubRelationTableService.lambdaQuery()
                    .eq(TargetSubRelationTable::getTargetId, targetSubAdd.getTargetId())
                    .eq(TargetSubRelationTable::getSubId, subId)
                    .one();
            if (ObjectUtil.isNull(relationTable)) {
                return ResultUtil.error(402, "子目标不存在/已删除");
            }
            if (!relationTable.getPreType().equals("1")) {
                //更新目标与子目标关联
                targetSubRelationTableService.lambdaUpdate()
                        .set(TargetSubRelationTable::getPreType, 1)
                        .eq(TargetSubRelationTable::getTargetId, targetSubAdd.getTargetId())
                        .eq(TargetSubRelationTable::getSubId, subId)
                        .update();
            }
        }
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("targetId", targetSubAdd.getTargetId());
        resultMap.put("subId", subId);
//        RepacigiSubTable build = RepacigiSubTable.builder().subId(subId).targetId(targetId).subName(name).build();
//        repacigiSubTableService.saveOrUpdate(build);
        return ResultUtil.success("基础信息更新成功", resultMap);
    }

    /**
     * 删除子目标
     *
     * @param targetId
     * @param subId
     * @return
     */
    @Override
    public synchronized Result<String> deleteSub(String targetId, String subId) throws SQLException {
        deleteService.deleteSub(targetId, subId);
        return ResultUtil.success("删除成功", null);
    }

    @Override
    public Result addTargetPosture(TargetPostureAdd targetPostureAdd, String userId) {
//        com.xinchuang.entity.targetSystem.target.TargetData targetData = targetMapper.findTargetOnly(targetPostureAdd.getTargetId());
//        if (ObjectUtil.isEmpty(targetData) || targetData.getDeleteSign() == 0) {
//            return ResultUtil.error(ResultEnum.TARGET_EMPTY);
//        }
        String name = null;
        String classify = null;
        for (TargetData data : targetPostureAdd.getPostureList()) {
            if (data.getKey().equals("targetName")) {
                name = data.getKeyValue();
            } else if (data.getKey().equals("targetClassify")) {
                classify = TargetUtil.getParamListOrString(data.getKeyValue());
            }
        }
        //判断类型是否存在
        if (ObjectUtil.isEmpty(postureTypeService.getById(classify))) {
            return ResultUtil.error(ResultEnum.TARGET_SUB_TYPE_IS_ERROR);
        }
        String postureId;
        TargetPostureRelationTable relationTable = null;
        if (StringUtils.isBlank(targetPostureAdd.getPostureId()) || targetPostureAdd.getPostureId().equals("0")) {
            postureId = String.valueOf(snow.nextId());
            relationTable = new TargetPostureRelationTable();
            relationTable.setTargetId(targetPostureAdd.getTargetId());
            relationTable.setPostureId(postureId);
            relationTable.setPreType(1);
        } else {
            postureId = targetPostureAdd.getPostureId();
            TargetPostureRelationTable table = targetPostureRelationTableService.lambdaQuery()
                    .eq(TargetPostureRelationTable::getTargetId, targetPostureAdd.getTargetId())
                    .eq(TargetPostureRelationTable::getPostureId, postureId)
                    .one();
            if (ObjectUtil.isNull(table)) {
                return ResultUtil.error(402, "子目标不存在/已删除");
            }
            table.setPreType(1);
        }
        TargetPostureMsgTable msg = targetPostureMsgTableService.getPostureMsgByTargetIdAndKeyIdAndKeyValue(targetPostureAdd.getTargetId(), "targetName", name);
        if (ObjectUtil.isNotNull(msg) && !msg.getPostureId().equals(postureId)) {
            return ResultUtil.error(402, "态势名称重复，请重新填写");
        }
        //更新目标与子目标关联
        if (ObjectUtil.isNotNull(relationTable)) {
            targetPostureRelationTableService.save(relationTable);
        }
        List<TargetPostureMsgTable> postureMsg =
                TargetUtil.getPostureMsg(postureId, targetPostureAdd.getPostureList(), userId, 1);
        //清理之前的数据
        targetPostureMsgTableService.lambdaUpdate()
                .eq(TargetPostureMsgTable::getPostureId, postureId)
                .eq(TargetPostureMsgTable::getMsgType, 1)
                .ne(TargetPostureMsgTable::getKeyId, "icon")
                .remove();
        if (CollectionUtil.isNotEmpty(postureMsg)) {
            //更新子目标基础信息
            targetPostureMsgTableService.saveBatch(postureMsg);
            redisUseService.updatePostureBase(postureId, postureMsg);
            redisUseService.updatePostureRelation(targetPostureAdd.getTargetId(), postureId);
        }
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("targetId", targetPostureAdd.getTargetId());
        resultMap.put("postureId", postureId);
        return ResultUtil.success("基础信息更新成功", resultMap);
    }

    @Override
    public Result<String> deletePosture(String targetId, String postureId) {
        deleteService.deletePosture(targetId, postureId);
        return ResultUtil.success("删除成功", null);
    }

    /**
     * 新增/修改体系关联关系
     *
     * @param targetId
     * @param list
     * @return
     */
    @Override
    public Result<Map<String, Object>> addRelation(String targetId, List<TargetRelation> list) {
        // 1.先查找已有的关系
        List<TargetRelation> targetRelations = targetRelationMapper.findByTargetId(targetId);
        if (null != targetRelations && !targetRelations.isEmpty()) {
            // 2.将已有的关系删除，将新的关系保存到数据库
            if (targetRelationMapper.deleteByTargetId(targetId) == 0) {
                return ResultUtil.error(500, ResultEnum.getByValue(500));
            }
        }
        if (null != list && !list.isEmpty()) {
            List<TargetRelation> listRelation = new ArrayList<>();
            Set<TargetRelation> set = new HashSet<>();
            for (TargetRelation targetRelation : list) {
                set.add(targetRelation);
            }
            for (TargetRelation targetRelation : set) {
                if (!targetRelation.getRelationId().equals(targetId)) {
                    targetRelation.setId(String.valueOf(snow.nextId()));
                    targetRelation.setTargetId(targetId);
                    targetRelation.setSource("WEB");
                    listRelation.add(targetRelation);
                }
            }
            if (CollectionUtil.isNotEmpty(listRelation)) {
                targetRelationMapper.save(listRelation);
            } else {
                return ResultUtil.error(404, "当前目标关联异常，请重试");
            }
        }
        return ResultUtil.success("目标关联关系修改成功");
    }

    /**
     * 查询子目标列表
     */
    @Override
    public Result<List<Map<String, Object>>> selectTargetSubList(String targetId) {
        com.xinchuang.entity.targetSystem.target.TargetData targetData = targetMapper.findTargetOnly(targetId);
        if (ObjectUtil.isEmpty(targetData) || targetData.getDeleteSign() == 0) {
            return ResultUtil.error(ResultEnum.TARGET_EMPTY);
        }
        List<Map<String, Object>> list = new ArrayList<>();
        List<TargetSubRelationTable> relationTables = targetSubRelationTableService
                .lambdaQuery()
                .eq(TargetSubRelationTable::getTargetId, targetId)
                .orderByDesc(TargetSubRelationTable::getUpdateTime)
                .list();
        if (CollectionUtil.isNotEmpty(relationTables)) {
            List<Map<String, Object>> old = new ArrayList<>();
            for (TargetSubRelationTable relationTable : relationTables) {
                Map<String, Object> baseData = redisUseService.getSubBaseData(relationTable.getSubId());
                if (null == baseData) {
                    continue;
                }
                if (1 == relationTable.getPreType()) {
                    baseData.put("zkwctype", 0);
                    list.add(baseData);
                } else {
                    baseData.put("zkwctype", 1);
                    old.add(baseData);
                }
//                List<TargetSubMsgTable> subMsgTables = targetSubMsgTableService.lambdaQuery()
//                        .eq(TargetSubMsgTable::getSubId, relationTable.getSubId())
//                        .eq(TargetSubMsgTable::getMsgType, 1)
//                        .list();
//                if (CollectionUtil.isNotEmpty(subMsgTables)) {
//                    Map<String, Object> subMsg = subListMsg(relationTable, subMsgTables);
//                    if (1 == relationTable.getPreType()) {
//                        subMsg.put("zkwctype", 0);
//                        list.add(subMsg);
//                    } else {
//                        subMsg.put("zkwctype", 1);
//                        old.add(subMsg);
//                    }
//                    subMsg.computeIfAbsent("icon", k -> keyWordSystem.getSERVER_URL() + "/icon/default.jpeg");
//                }
            }
            list.addAll(old);
        }
        return ResultUtil.success("查询成功", list);
    }

    @Override
    public Result selectTargetPostureList(String targetId) {
        com.xinchuang.entity.targetSystem.target.TargetData targetData = targetMapper.findTargetOnly(targetId);
        if (ObjectUtil.isEmpty(targetData) || targetData.getDeleteSign() == 0) {
            return ResultUtil.error(ResultEnum.TARGET_EMPTY);
        }
        List<Map<String, Object>> list = new ArrayList<>();
        List<TargetPostureRelationTable> relationTables = targetPostureRelationTableService
                .lambdaQuery()
                .eq(TargetPostureRelationTable::getTargetId, targetId)
                .orderByDesc(TargetPostureRelationTable::getUpdateTime)
                .list();
        if (CollectionUtil.isNotEmpty(relationTables)) {
            for (TargetPostureRelationTable relationTable : relationTables) {
                Map<String, Object> baseData = redisUseService.getPostureBaseData(relationTable.getPostureId());
                if (null == baseData) {
                    continue;
                }
                list.add(baseData);
//                List<TargetPostureMsgTable> subMsgTables = targetPostureMsgTableService.lambdaQuery()
//                        .eq(TargetPostureMsgTable::getPostureId, relationTable.getPostureId())
//                        .eq(TargetPostureMsgTable::getMsgType, 1)
//                        .list();
//                if (CollectionUtil.isNotEmpty(subMsgTables)) {
//                    Map<String, Object> map = postureListMsg(relationTable, subMsgTables);
//                    map.computeIfAbsent("icon", k -> keyWordSystem.getSERVER_URL() + "/icon/default.jpeg");
//                    list.add(map);
//                }
            }
        }
        return ResultUtil.success("查询成功", list);
    }

    private Map<String, Object> subListMsg(TargetSubRelationTable relationTable, List<TargetSubMsgTable> subMsgTables) {
        Map<String, Object> map = new HashMap<>();
        map.put("subId", relationTable.getSubId());
        map.put("targetName", "");
        map.put("targetClassify", "");
        map.put("position", new ArrayList<>());
        map.put("icon", null);
        for (TargetSubMsgTable subMsgTable : subMsgTables) {
            switch (subMsgTable.getKeyId()) {
                case "position":
                    map.put("position", FileElseUtil.getStringTransitionList(subMsgTable.getKeyValue()));
                    break;
                case "icon":
                    map.put("icon", keyWordSystem.getSERVER_URL() + subMsgTable.getKeyValue());
                    break;
                case "targetName":
                    map.put("targetName", subMsgTable.getKeyValue());
                    break;
                case "targetClassify":
                    map.put("targetClassify", TargetUtil.getParamListOrString(subMsgTable.getKeyValue()));
                    break;
                default:
                    break;
            }
        }
        SystemPosition position = systemPositionMapper.getPositionById(relationTable.getSubId());
        if (ObjectUtil.isNotNull(position)) {
            map.put("viewDistances", FileElseUtil.getStringTransitionList(position.getViewDistances()));
            double height = FileElseUtil.getStringTransitionDouble(position.getHeight());
            map.put("height", height == 0 ? null : height);
        } else {
            map.put("viewDistances", new ArrayList<>());
            map.put("height", null);
        }
        return map;
    }

    private Map<String, Object> postureListMsg(TargetPostureRelationTable relationTable, List<TargetPostureMsgTable> postureMsgTables) {
        Map<String, Object> map = new HashMap<>();
        map.put("postureId", relationTable.getPostureId());
        map.put("targetName", "");
        map.put("targetClassify", "");
        map.put("position", new ArrayList<>());
        map.put("icon", null);
        for (TargetPostureMsgTable postureMsgTable : postureMsgTables) {
            switch (postureMsgTable.getKeyId()) {
                case "position":
                    map.put("position", FileElseUtil.getStringTransitionList(postureMsgTable.getKeyValue()));
                    break;
                case "icon":
                    map.put("icon", keyWordSystem.getSERVER_URL() + postureMsgTable.getKeyValue());
                    break;
                case "targetName":
                    map.put("targetName", postureMsgTable.getKeyValue());
                    break;
                case "targetClassify":
                    map.put("targetClassify", TargetUtil.getParamListOrString(postureMsgTable.getKeyValue()));
                    break;
                default:
                    break;
            }
        }
        SystemPosition position = systemPositionMapper.getPositionById(relationTable.getPostureId());
        if (ObjectUtil.isNotNull(position)) {
            map.put("viewDistances", FileElseUtil.getStringTransitionList(position.getViewDistances()));
            double height = FileElseUtil.getStringTransitionDouble(position.getHeight());
            map.put("height", height == 0 ? null : height);
        } else {
            map.put("viewDistances", new ArrayList<>());
            map.put("height", null);
        }
        return map;
    }

    /**
     * 新增/更新目标详细信息
     *
     * @param targetAdd
     * @param userId
     * @return
     */
    @Override
    public Result<Map<String, Object>> addTargetElse(TargetAdd targetAdd, String userId) {
        com.xinchuang.entity.targetSystem.target.TargetData targetData = targetMapper.findTargetOnly(targetAdd.getTargetId());
        if (ObjectUtil.isEmpty(targetData) || targetData.getDeleteSign() == 0) {
            return ResultUtil.error(ResultEnum.TARGET_EMPTY);
        }
//        List<TargetMsgTable> targetMsg = TargetUtil.getTargetMsg(targetData, targetAdd.getTargetId(), targetAdd, userId, 2);
        if (CollectionUtil.isNotEmpty(targetAdd.getTargetList())) {
            List<TargetMsgTable> list = targetMsgTableService.lambdaQuery()
                    .eq(TargetMsgTable::getRedId, targetAdd.getTargetId())
                    .eq(TargetMsgTable::getMsgType, 2)
                    .list();
            List<TargetMsgTable> elseMessage = TargetUtil.getTargetElseMessage(targetAdd, list, userId, 2);
            //更新目标double数据的汇总
            redisUseService.updateTargetBase(targetData.getTargetId(), elseMessage);
            //清理之前的数据
            targetMsgTableService.lambdaUpdate()
                    .eq(TargetMsgTable::getRedId, targetAdd.getTargetId())
                    .eq(TargetMsgTable::getMsgType, 2)
                    .remove();
            targetMsgTableService.saveOrUpdateBatch(elseMessage);
            redisUseService.updateTargetSpecial(targetAdd.getTargetId(), elseMessage);
        }
        return ResultUtil.success("详细信息更新成功", null);
    }

    /**
     * 子目标详细信息维护
     *
     * @param targetId
     * @param subId
     * @param list
     * @param userId
     * @return
     */
    @Override
    public Result<Map<String, Object>> targetSubDetailMaintain(String targetId, String subId, List<TargetData> list, String userId) throws SQLException {
        com.xinchuang.entity.targetSystem.target.TargetData targetData = targetMapper.findTargetOnly(targetId);
        if (ObjectUtil.isNull(targetData) || targetData.getDeleteSign() == 0) {
            return ResultUtil.error(ResultEnum.TARGET_EMPTY);
        }
//        List<TargetSubMsgTable> subMsgs = TargetUtil.getSubMsg(subId, list, userId, 2);
        if (CollectionUtil.isNotEmpty(list)) {
            List<TargetSubMsgTable> tables = targetSubMsgTableService.lambdaQuery()
                    .eq(TargetSubMsgTable::getSubId, subId)
                    .eq(TargetSubMsgTable::getMsgType, 2)
                    .list();
            List<TargetSubMsgTable> subElseMessage = TargetUtil.getSubElseMessage(subId, list, tables, userId, 2);
            //更新子目标double数据的汇总
            redisUseService.updateSubBase(subId, subElseMessage);
            //清理之前的数据
            targetSubMsgTableService.lambdaUpdate()
                    .eq(TargetSubMsgTable::getSubId, subId)
                    .eq(TargetSubMsgTable::getMsgType, 2)
                    .remove();
            targetSubMsgTableService.saveOrUpdateBatch(subElseMessage);
            redisUseService.updateSubSpecial(subId, subElseMessage);
        }
        return ResultUtil.success("详细信息更新成功", null);
    }

    @Override
    public Result<Map<String, Object>> targetPostureDetailMaintain(String targetId, String postureId, List<TargetData> list, String userId) {
//        com.xinchuang.entity.targetSystem.target.TargetData targetData = targetMapper.findTargetOnly(targetId);
//        if (ObjectUtil.isNull(targetData) || targetData.getDeleteSign() == 0) {
//            return ResultUtil.error(ResultEnum.TARGET_EMPTY);
//        }
        List<TargetPostureMsgTable> postureMsgTables = TargetUtil.getPostureMsg(postureId, list, userId, 2);
        if (CollectionUtil.isNotEmpty(postureMsgTables)) {
            //清理之前的数据
            targetPostureMsgTableService.lambdaUpdate()
                    .eq(TargetPostureMsgTable::getPostureId, postureId)
                    .eq(TargetPostureMsgTable::getMsgType, 2)
                    .remove();
            targetPostureMsgTableService.saveBatch(postureMsgTables);
            redisUseService.updatePostureBase(postureId, postureMsgTables);
        }
        return ResultUtil.success("详细信息更新成功", null);
    }

    /**
     * 查询子目标基础信息
     *
     * @param targetId
     * @param subId
     * @return
     */
    @Override
    public Result<Map<String, Object>> getSubBase(String targetId, String subId) throws SQLException {
        com.xinchuang.entity.targetSystem.target.TargetData targetData = targetMapper.findTargetOnly(targetId);
        if (ObjectUtil.isEmpty(targetData) || targetData.getDeleteSign() == 0) {
            return ResultUtil.error(ResultEnum.TARGET_EMPTY);
        }
        Map<String, Object> map = new HashMap<>();
        List<CommonAttribute> commonAttributes = commonMapper.findCommons(2);
        TargetUtil.getCommonAttributesList(map, commonAttributes);
        List<TargetSubMsgTable> list = targetSubMsgTableService.lambdaQuery().eq(TargetSubMsgTable::getSubId, subId).list();
        if (CollectionUtil.isNotEmpty(list)) {
            TargetUtil.getSubMsg(map, list);
        }
        return ResultUtil.success("查询成功", map);
    }

    /**
     * 查询子目标详细信息
     *
     * @param targetId
     * @param subId
     * @return
     */
    @Override
    public Result<Map<String, Object>> getSubDetail(String targetId, String subId) throws SQLException {
        com.xinchuang.entity.targetSystem.target.TargetData targetData = targetMapper.findTargetOnly(targetId);
        if (null == targetData || targetData.getDeleteSign() == 0) {
            return ResultUtil.error(ResultEnum.TARGET_EMPTY);
        }
        HashMap<String, Object> resultMap = new HashMap<>();
        TargetSubMsgTable classify = targetSubMsgTableService.lambdaQuery()
                .eq(TargetSubMsgTable::getSubId, subId)
                .eq(TargetSubMsgTable::getKeyId, "targetClassify")
                .one();
        if (ObjectUtil.isNotNull(classify)) {
            String type = TargetUtil.getParamListOrString(classify.getKeyValue());
            List<SpecialAttribute> types = targetTypeMapper.findSpecialByTypeId(type);
            TargetUtil.getSpecialAttributesList(resultMap, types);
            List<TargetSubMsgTable> list = targetSubMsgTableService.lambdaQuery()
                    .eq(TargetSubMsgTable::getSubId, subId)
                    .eq(TargetSubMsgTable::getMsgType, 2)
                    .list();
            TargetUtil.getSubMsg(resultMap, list);
        }
        return ResultUtil.success("查询成功", resultMap);
    }

    @Override
    public Result<Map<String, Object>> getPostureBase(String targetId, String postureId) {
//        com.xinchuang.entity.targetSystem.target.TargetData targetData = targetMapper.findTargetOnly(targetId);
//        if (ObjectUtil.isEmpty(targetData) || targetData.getDeleteSign() == 0) {
//            return ResultUtil.error(ResultEnum.TARGET_EMPTY);
//        }
        Map<String, Object> map = new HashMap<>();
        List<TargetPostureMsgTable> list = targetPostureMsgTableService
                .lambdaQuery()
                .eq(TargetPostureMsgTable::getPostureId, postureId)
                .eq(TargetPostureMsgTable::getMsgType, "1")
                .list();
        if (CollectionUtil.isNotEmpty(list)) {
            TargetUtil.getPostureMsg(map, list);
        }
        return ResultUtil.success("查询成功", map);
    }

    @Override
    public Result<Map<String, Object>> getPostureDetail(String targetId, String postureId) {
//        com.xinchuang.entity.targetSystem.target.TargetData targetData = targetMapper.findTargetOnly(targetId);
//        if (ObjectUtil.isEmpty(targetData) || targetData.getDeleteSign() == 0) {
//            return ResultUtil.error(ResultEnum.TARGET_EMPTY);
//        }
        TargetPostureMsgTable postureMsgTable = targetPostureMsgTableService
                .lambdaQuery()
                .eq(TargetPostureMsgTable::getPostureId, postureId)
                .eq(TargetPostureMsgTable::getKeyId, "targetClassify")
                .one();
        Map<String, Object> map = new HashMap<>();
        if (ObjectUtil.isNotNull(postureMsgTable)) {
            List<PostureAttribute> postureAttributes = postureAttributeService.lambdaQuery().eq(PostureAttribute::getTypeId, TargetUtil.getParamListOrString(postureMsgTable.getKeyValue())).list();
            TargetUtil.getPostureAttributesList(map, postureAttributes);
        }
        List<TargetPostureMsgTable> list = targetPostureMsgTableService
                .lambdaQuery()
                .eq(TargetPostureMsgTable::getPostureId, postureId)
                .eq(TargetPostureMsgTable::getMsgType, "2")
                .list();
        if (CollectionUtil.isNotEmpty(list)) {
            TargetUtil.getPostureMsg(map, list);
        }
        return ResultUtil.success("查询成功", map);
    }

    @Override
    public Result deleteTargetRelation(String id) {
        int result = targetRelationMapper.deleteTargetRelation(id);
        if (result == 0) {
            return ResultUtil.error(ResultEnum.DELETE_ERROR);
        }
        return ResultUtil.success("删除成功", null);
    }

    @Override
    public Result<List<Map<String, Object>>> getTargetToMap(List<String> targetIdList) {
        if (CollectionUtil.isEmpty(targetIdList)) {
            return ResultUtil.error(ResultEnum.SELECT_EMPTY);
        }
        List<com.xinchuang.entity.targetSystem.target.TargetData> targetDataList = targetMapper.getTargetList(targetIdList);
        if (CollectionUtil.isNotEmpty(targetDataList)) {
            List<Map<String, Object>> resultList = new ArrayList<>();
            for (com.xinchuang.entity.targetSystem.target.TargetData targetData : targetDataList) {
                if (judgeStringNotNull(targetData.getLon(), targetData.getLat())) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("targetName", targetData.getTargetName());
                    List<Double> list = new ArrayList<>();
                    list.add(AreaUtil.rad(targetData.getLon()));
                    list.add(AreaUtil.rad(targetData.getLat()));
                    list.add(null == targetData.getHeight() ? 0 : targetData.getHeight());
                    map.put("position", list);
                    map.put("lon", targetData.getLon());
                    map.put("lat", targetData.getLat());
                    map.put("height", targetData.getHeight());
//                    map.put("targetType", targetData.getTargetClassify());
//                    String sign = targetTypeMapper.getSign(MyUtil.classToString(targetData.getTargetType()));
//                    map.put("icon", StringUtils.isNotBlank(sign) ? this.keyWordSystem.getSERVER_URL() + "/sign/" + sign : null);
                    map.put("targetType", redisUseService.getTypeName(targetData.getType()));
                    String sign = redisUseService.getTypeSign(targetData.getType());
                    map.put("icon", this.keyWordSystem.getSERVER_URL() + "/sign/" + sign);
                    resultList.add(map);
                }
            }
            return ResultUtil.success(resultList);
        }
        return ResultUtil.error(ResultEnum.SELECT_EMPTY);
    }

    @Override
    public Result<List<Map<String, Object>>> toMap(int pageNum, int pageSize, String keyword, String country, String targetType, Integer common) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        //常用目标定位
        if (null != common && common == 1) {
            Map<Object, Object> hmget = redisUtil.hmget(this.keyWordSystem.getVERSION() + "-COMMON-SORT");
            if (CollectionUtil.isNotEmpty(hmget)) {
                List<Map.Entry<Object, Object>> list = new ArrayList<Map.Entry<Object, Object>>(hmget.entrySet());
                Collections.sort(list, new Comparator<Map.Entry<Object, Object>>() {
                    @Override
                    public int compare(Map.Entry<Object, Object> o1, Map.Entry<Object, Object> o2) {
                        int key1 = Integer.parseInt(o1.getValue().toString());
                        int key2 = Integer.parseInt(o2.getValue().toString());
                        if (key1 == key2) {
                            return 0;
                        } else {
                            return key1 < key2 ? 1 : -1;
                        }
                    }
                });
                Map<String, Object> map = null;
                for (int i = 0, j = list.size(); i < j; i++) {
                    if (i > 9) {
                        break;
                    }
                    Map.Entry<Object, Object> entry = list.get(i);
                    map = new HashMap<>();
                    com.xinchuang.entity.targetSystem.target.TargetData only = targetMapper.findTargetOnly(entry.getKey().toString());
                    if (null != only) {
                        if (judgeStringNotNull(only.getLon(), only.getLat())) {
                            map.put("targetName", only.getTargetName());
                            List<Double> position = new ArrayList<>();
                            position.add(AreaUtil.rad(only.getLon()));
                            position.add(AreaUtil.rad(only.getLat()));
                            position.add(null == only.getHeight() ? 0 : only.getHeight());
                            map.put("position", position);
                            //图标
//                            map.put("targetType", targetTypeMapper.getTypeName(only.getTargetClassify()));
//                            String sign = targetTypeMapper.getSign(MyUtil.classToString(only.getTargetClassify()));
//                            map.put("icon", StringUtils.isNotBlank(sign) ? this.keyWordSystem.getSERVER_URL() + "/sign/" + sign : null);
                            map.put("targetType", redisUseService.getTypeName(only.getType()));
                            String sign = redisUseService.getTypeSign(only.getType());
                            map.put("icon", this.keyWordSystem.getSERVER_URL() + "/sign/" + sign);
                            resultList.add(map);
                        }
                    }
                }
            }
            return ResultUtil.success(resultList);
        }
        if (StringUtils.isBlank(keyword)) {
            keyword = null;
        }
        List<String> countrys = null;
        if (StringUtils.isNotBlank(country)) {
            countrys = new ArrayList<>();
            countrys.addAll(FileElseUtil.getStringTransitionList(country));
        }
        List<String> type = null;
        List<String> types = null;
        if (StringUtils.isNotBlank(targetType)) {
            type = new ArrayList<>();
            type.addAll(FileElseUtil.getStringTransitionList(targetType));
        }
        boolean c = false;
        //封装类型查询
        if (CollectionUtil.isNotEmpty(type)) {
            types = new ArrayList<>();
            for (String s : type) {
                String typeId = targetTypeMapper.getTypeId(s);
                if (StringUtils.isNotBlank(typeId)) {
                    types.add(typeId);
                }
            }
        }
//        PageHelper.startPage(pageNum, pageSize);
//        List<com.xinchuang.entity.targetSystem.target.TargetData> data = targetMapper.getTargetMap(keyword, countrys, type);
//        PageHelper.startPage(pageNum, pageSize);
//        List<com.xinchuang.entity.targetSystem.target.TargetData> data = null;
//        if (c) {
//            data = targetMapper.findAll(countryList, types, keyword);
//        } else {
//            data = targetMapper.findAll(countrys, types, keyword);
//        }
//        PageInfo<com.xinchuang.entity.targetSystem.target.TargetData> pageInfo = new PageInfo<>(data);
        Page<TargetBaseData> pageInfo = targetBaseDataService.lambdaQuery()
                .in(CollectionUtil.isNotEmpty(countrys), TargetBaseData::getCountry, countrys)
                .in(CollectionUtil.isNotEmpty(types), TargetBaseData::getType, types)
                .like(StringUtils.isNotBlank(keyword), TargetBaseData::getTargetName, keyword)
                .eq(TargetBaseData::getDeleteSign, 1)
                .orderByDesc(TargetBaseData::getCreateTime)
                .page(new Page<>(pageNum, pageSize));
        if (CollectionUtil.isNotEmpty(pageInfo.getRecords())) {
            for (TargetBaseData targetData : pageInfo.getRecords()) {
                Map<String, Object> map = new HashMap<>();
                map.put("targetName", targetData.getTargetName());
                map.put("position", redisUseService.getViewPositionRad(targetData.getTargetId()));
                //图标
                map.put("targetType", redisUseService.getTypeName(targetData.getType()));
                String sign = redisUseService.getTypeSign(targetData.getType());
                map.put("icon", this.keyWordSystem.getSERVER_URL() + "/sign/" + sign);
                resultList.add(map);
            }
        }
        return ResultUtil.success(resultList);
    }

    @Override
    public Result sysToMapAll(String id, String sysId, Integer type) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        if (null != type) {
            List<com.xinchuang.entity.targetSystem.target.TargetData> dataList = null;
            if (type == 1) {
                dataList = systemRelationMapper.selectSystemRelationTarget(id);
            } else if (type == 2) {
                SystemsMaster master = systemsMasterMapper.selectSystemsOnly(id);
                if (ObjectUtil.isNotEmpty(master)) {
                    dataList = new ArrayList<>();
                    List<com.xinchuang.entity.targetSystem.target.TargetData> targets = targetMapper.getSystemsTargets(id);
                    if (CollectionUtil.isNotEmpty(targets)) {
                        dataList.addAll(targets);
                    }
                }
            }
            if (CollectionUtil.isNotEmpty(dataList)) {
                for (com.xinchuang.entity.targetSystem.target.TargetData targetData : dataList) {
                    if (judgeStringNotNull(targetData.getLon(), targetData.getLat())) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("targetId", targetData.getTargetId());
                        map.put("targetName", targetData.getTargetName());
                        map.put("position", Arrays.asList(AreaUtil.rad(targetData.getLon()), AreaUtil.rad(targetData.getLat()), targetData.getHeight()));
//                        map.put("targetType", targetTypeMapper.getTypeName(targetData.getType()));
//                        String sign = targetTypeMapper.getSign(targetData.getType());
//                        map.put("icon", StringUtils.isNotBlank(sign) ? this.keyWordSystem.getSERVER_URL() + "/sign/" + sign : null);
                        //图标
                        map.put("targetType", redisUseService.getTypeName(targetData.getType()));
                        String sign = redisUseService.getTypeSign(targetData.getType());
                        map.put("icon", this.keyWordSystem.getSERVER_URL() + "/sign/" + sign);
                        map.put("radius", null != targetData.getRangeValue() ? targetData.getRangeValue() : 0);
                        resultList.add(map);
                    }
                }
            }
        }
        return ResultUtil.success(resultList);
    }

    @Override
    public Result<Map<String, Object>> getTargetAndSubOneToMap(String targetId) throws SQLException {
        com.xinchuang.entity.targetSystem.target.TargetData targetData = targetMapper.findTargetOnly(targetId);
        if (ObjectUtil.isNull(targetData) || targetData.getDeleteSign() == 0) {
            return ResultUtil.error(ResultEnum.TARGET_EMPTY);
        }
        Map<String, Object> resultMap = redisUseService.getTargetMapRedisData(targetData.getTargetId(), targetData.getType());
//        Map<String, Object> resultMap = new HashMap<>();
//        //获取场景数据
//        SystemPosition position = systemPositionMapper.getPositionById(targetId);
//        if (null != position) {
//            resultMap.put("height", StringUtils.isNotBlank(position.getHeight()) ? position.getHeight() : null);
//            resultMap.put("viewDistances", StringUtils.isNotBlank(position.getViewDistances()) ? FileElseUtil.getStringTransitionList(position.getViewDistances()) : new ArrayList<>());
//        } else {
//            resultMap.put("height", null);
//            resultMap.put("viewDistances", new ArrayList<>());
//        }
//        resultMap.put("targetName", targetData.getTargetName());
//        //基础属性参数初始化
//        resultMap.put("position", new ArrayList<>());
//        resultMap.put("area", 0);
//        resultMap.put("plotinfoobj", "");
//        resultMap.put("targetType", "");
//        resultMap.put("icon", null);
//        resultMap.put("signList", new ArrayList<>());
//        List<TargetMsgTable> msgTables = targetMsgTableService.lambdaQuery()
//                .eq(TargetMsgTable::getRedId, targetId)
//                .in(TargetMsgTable::getKeyId, "position", "area", "plotinfoobj")
//                .eq(TargetMsgTable::getMsgType, 1)
//                .list();
//        if (CollectionUtil.isNotEmpty(msgTables)) {
//            for (TargetMsgTable msgTable : msgTables) {
//                switch (msgTable.getKeyId()) {
//                    case "position":
//                        resultMap.put("position", FileElseUtil.getStringTransitionList(msgTable.getKeyValue()));
//                        break;
//                    case "area":
//                        resultMap.put("area", FileElseUtil.getStringTransitionDouble(msgTable.getKeyValue()));
//                        break;
//                    case "plotinfoobj":
//                        resultMap.put("plotinfoobj", FileElseUtil.getStringTransitionString(msgTable.getKeyValue()));
//                        break;
//                    default:
//                        break;
//                }
//            }
//        }
//        //目标类型与类型图标查询
//        if (StringUtils.isNotBlank(targetData.getType())) {
////            String typeName = targetTypeMapper.getTypeName(targetData.getType());
////            String sign = targetTypeMapper.getSign(targetData.getType());
//            resultMap.put("targetType", redisUseService.getTypeName(targetData.getType()));
//            String sign = redisUseService.getTypeSign(targetData.getType());
//            resultMap.put("icon", this.keyWordSystem.getSERVER_URL() + "/sign/" + sign);
//        }
        //标签管理查询
//        List<TargetElse> targetElses = targetElseMapper.selectTargetElseIcon(targetId, "true");
//        if (CollectionUtil.isNotEmpty(targetElses)) {
//            List<Map<String, Object>> resultList = new ArrayList<>();
//            Map<String, Object> map = null;
//            for (TargetElse targetEls : targetElses) {
//                map = new HashMap<>();
//                map.put("id", targetEls.getId());
//                map.put("name", targetEls.getName());
//                map.put("address", targetEls.getAddress());
//                map.put("reveal", targetEls.getMessage());
//                map.put("icon", targetEls.getStatus());
//                map.put("remark", targetEls.getRemark());
//                resultList.add(map);
//            }
//            resultMap.put("signList", resultList);
//        }
        //子类目标查询
        List<Map<String, Object>> subLists = new ArrayList<>();
        //子目标
        subMap(subLists, targetId);
        //态势
        postureMap(subLists, targetId);
        resultMap.put("subList", subLists);
        return ResultUtil.success(resultMap);
    }

    private void subMap(List<Map<String, Object>> subLists, String targetId) {
        //查询目标与子目标关联
        List<TargetSubRelationTable> relationTables = targetSubRelationTableService.lambdaQuery()
                .eq(TargetSubRelationTable::getTargetId, targetId)
                .eq(TargetSubRelationTable::getPreType, 1)
                .list();
        if (CollectionUtil.isNotEmpty(relationTables)) {
//            Map<String, Object> m;
            for (TargetSubRelationTable relationTable : relationTables) {
                Map<String, Object> map = redisUseService.getSubMapRedisData(relationTable.getSubId());
                if (null != map) {
                    subLists.add(map);
                }
//                m = new HashMap<>();
//                m.put("subName", "");
//                m.put("position", new ArrayList<>());
//                m.put("height", 0);
//                m.put("area", 0);
//                m.put("plotinfoobj", "");
//                m.put("targetType", "");
//                m.put("icon", null);
//                m.put("signList", new ArrayList<>());
//                m.put("imgList", new ArrayList<>());
//                m.put("modelList", new ArrayList<>());
//                m.put("angle", null);
//                //子目标封装
//                List<TargetSubMsgTable> subMsgTables = targetSubMsgTableService.lambdaQuery()
//                        .eq(TargetSubMsgTable::getSubId, relationTable.getSubId())
//                        .in(TargetSubMsgTable::getKeyId, "targetName", "position", "height", "area", "plotinfoobj", "targetClassify")
//                        .list();
//                String classify = null;
//                if (CollectionUtil.isNotEmpty(subMsgTables)) {
//                    for (TargetSubMsgTable subMsgTable : subMsgTables) {
//                        switch (subMsgTable.getKeyId()) {
//                            case "targetName":
//                                m.put("subName", FileElseUtil.getStringTransitionString(subMsgTable.getKeyValue()));
//                                break;
//                            case "position":
//                                m.put("position", FileElseUtil.getStringTransitionList(subMsgTable.getKeyValue()));
//                                break;
//                            case "height":
//                                m.put("height", FileElseUtil.getStringTransitionDouble(subMsgTable.getKeyValue()));
//                                break;
//                            case "area":
//                                m.put("area", FileElseUtil.getStringTransitionDouble(subMsgTable.getKeyValue()));
//                                break;
//                            case "plotinfoobj":
//                                m.put("plotinfoobj", FileElseUtil.getStringTransitionString(subMsgTable.getKeyValue()));
//                                break;
//                            case "targetClassify":
//                                classify = TargetUtil.getParamListOrString(subMsgTable.getKeyValue());
//                                break;
//                            default:
//                                break;
//                        }
//                    }
//                }
//                if (StringUtils.isNotBlank(classify)) {
////                    String typeName = targetTypeMapper.getTypeName(classify);
////                    m.put("targetType", StringUtils.isNotBlank(typeName) ? typeName : "");
////                    String sign = targetTypeMapper.getSign(classify);
////                    m.put("icon", StringUtils.isNotBlank(sign) ? this.keyWordSystem.getSERVER_URL() + "/sign/" + sign : null);
//                    m.put("targetType", redisUseService.getTypeName(classify));
//                    String sign = redisUseService.getTypeSign(classify);
//                    m.put("icon", this.keyWordSystem.getSERVER_URL() + "/sign/" + sign);
//                }
////                List<TargetElse> subElses = targetElseMapper.selectTargetElseSubIcon(targetId, relationTable.getSubId(), "true");
////                if (CollectionUtil.isNotEmpty(subElses)) {
////                    List<Map<String, Object>> resultList = new ArrayList<>();
////                    Map<String, Object> subMap = null;
////                    for (TargetElse targetEls : subElses) {
////                        subMap = new HashMap<>();
////                        subMap.put("id", targetEls.getId());
////                        subMap.put("name", targetEls.getName());
////                        subMap.put("address", targetEls.getAddress());
////                        subMap.put("reveal", targetEls.getMessage());
////                        subMap.put("icon", targetEls.getStatus());
////                        subMap.put("remark", targetEls.getRemark());
////                        resultList.add(subMap);
////                    }
////                    m.put("signList", resultList);
////                }
//                subLists.add(m);
            }
        }
    }

    private void postureMap(List<Map<String, Object>> subLists, String targetId) {
        //查询目标与子目标关联
        List<TargetPostureRelationTable> relationTables = targetPostureRelationTableService.lambdaQuery()
                .eq(TargetPostureRelationTable::getTargetId, targetId)
                .eq(TargetPostureRelationTable::getPreType, 1)
                .list();
        if (CollectionUtil.isNotEmpty(relationTables)) {
//            Map<String, Object> m;
            for (TargetPostureRelationTable relationTable : relationTables) {
                Map<String, Object> map = redisUseService.getPostureMapRedisData(relationTable.getPostureId());
                if (null != map) {
                    subLists.add(map);
                }
//                m = new HashMap<>();
//                m.put("subName", "");
//                m.put("position", new ArrayList<>());
//                m.put("height", 0);
//                m.put("area", 0);
//                m.put("plotinfoobj", "");
//                m.put("targetType", "");
//                m.put("icon", null);
//                m.put("signList", new ArrayList<>());
//                m.put("imgList", new ArrayList<>());
//                m.put("modelList", new ArrayList<>());
//                m.put("angle", null);
//                //子目标封装
//                List<TargetPostureMsgTable> postureMsgTables = targetPostureMsgTableService.lambdaQuery()
//                        .eq(TargetPostureMsgTable::getPostureId, relationTable.getPostureId())
//                        .in(TargetPostureMsgTable::getKeyId, "targetName", "position", "targetClassify", "plotinfoobj")
//                        .list();
//                String classify = null;
//                if (CollectionUtil.isNotEmpty(postureMsgTables)) {
//                    for (TargetPostureMsgTable postureMsgTable : postureMsgTables) {
//                        switch (postureMsgTable.getKeyId()) {
//                            case "targetName":
//                                m.put("subName", FileElseUtil.getStringTransitionString(postureMsgTable.getKeyValue()));
//                                break;
//                            case "position":
//                                m.put("position", FileElseUtil.getStringTransitionList(postureMsgTable.getKeyValue()));
//                                break;
//                            case "targetClassify":
//                                classify = TargetUtil.getParamListOrString(postureMsgTable.getKeyValue());
//                                break;
//                            case "plotinfoobj":
//                                m.put("plotinfoobj", FileElseUtil.getStringTransitionString(postureMsgTable.getKeyValue()));
//                                break;
//                        }
//                    }
//                }
//                if (StringUtils.isNotBlank(classify)) {
////                    String typeName = targetTypeMapper.getTypeName(classify);
////                    m.put("targetType", StringUtils.isNotBlank(typeName) ? typeName : "");
////                    String sign = targetTypeMapper.getSign(classify);
////                    m.put("icon", StringUtils.isNotBlank(sign) ? this.keyWordSystem.getSERVER_URL() + "/sign/" + sign : null);
//                    m.put("targetType", redisUseService.getTypeName(classify));
//                    String sign = redisUseService.getTypeSign(classify);
//                    m.put("icon", this.keyWordSystem.getSERVER_URL() + "/sign/" + sign);
//                }
////                List<TargetElse> subElses = targetElseMapper.selectTargetElseSubIcon(targetId, relationTable.getPostureId(), "true");
////                if (CollectionUtil.isNotEmpty(subElses)) {
////                    List<Map<String, Object>> resultList = new ArrayList<>();
////                    Map<String, Object> subMap = null;
////                    for (TargetElse targetEls : subElses) {
////                        subMap = new HashMap<>();
////                        subMap.put("id", targetEls.getId());
////                        subMap.put("name", targetEls.getName());
////                        subMap.put("address", targetEls.getAddress());
////                        subMap.put("reveal", targetEls.getMessage());
////                        subMap.put("icon", targetEls.getStatus());
////                        subMap.put("remark", targetEls.getRemark());
////                        resultList.add(subMap);
////                    }
////                    m.put("signList", resultList);
////                }
//                subLists.add(m);
            }
        }
    }

    @Override
    public Result getSystemToMap(String sysId, String targetId) {
        Map<String, Object> resultMap = new HashMap<>();
        Set<String> targetList = new HashSet<>();
        boolean isTarget = true;
        //查询体系关联关系
        List<SystemsRelationship> list = null;
        if (StringUtils.isNotBlank(targetId)) {
            list = targetMapper.getSystemsTargetToMap(sysId, targetId);
            isTarget = false;
        } else {
            list = targetMapper.getSystemsToMap(sysId);
        }
        //查询的体系
        Set<String> targetIds = new HashSet<>();
        if (StringUtils.isNotBlank(targetId)) {
            targetIds.add(targetId);
        }
        //当前体系所有关联目标
        List<String> systemsTargetList = redisUseService.getSystemsTargetList(sysId);

        if (CollectionUtil.isEmpty(systemsTargetList)) {
            systemsTargetList = new ArrayList<>();
        }

        Map<Object, Object> relation = redisUseService.getSystemsRelation(sysId);
        if (CollectionUtil.isNotEmpty(relation)) {
            for (Object id : relation.keySet()) {
                List<String> subIds = redisUseService.getSystemsTargetList(id.toString());
                if (CollectionUtil.isNotEmpty(subIds)) {
                    systemsTargetList.addAll(subIds);
                }
            }
        }

        if (CollectionUtil.isNotEmpty(list)) {
            List<Object> points = new ArrayList<>();
            Map<String, Map<String, Object>> mainMap = new HashMap<>();
            Map<String, Set<String>> setMap = new HashMap<>();
            for (SystemsRelationship relationship : list) {
                if (!systemsTargetList.contains(relationship.getTargetOne())
                        || !systemsTargetList.contains(relationship.getTargetTwo())) {
                    continue;
                }
                //查询目标基本信息
                if (redisUtil.hasKey(RedisName.TARGET_BASE_DATA_ALL + "_" + relationship.getTargetOne())
                        && redisUtil.hasKey(RedisName.TARGET_BASE_DATA_ALL + "_" + relationship.getTargetTwo())
                ) {
                    targetIds.add(relationship.getTargetOne());
                    targetIds.add(relationship.getTargetTwo());
                    Map<String, Object> poineMap;
                    Set<String> nameSet;
                    String one = relationship.getTargetOne() + "&&" + relationship.getTargetTwo();
                    String two = relationship.getTargetTwo() + "&&" + relationship.getTargetOne();
                    if (null != mainMap.get(one)) {
                        poineMap = mainMap.get(one);
                        nameSet = setMap.get(one);
                        nameSet.add(relationship.getRelationType());
                        setMap.put(one, nameSet);
                    } else if (null != mainMap.get(two)) {
                        poineMap = mainMap.get(two);
                        nameSet = setMap.get(two);
                        nameSet.add(relationship.getRelationType());
                        setMap.put(two, nameSet);
                    } else {
                        poineMap = new HashMap<>();
                        nameSet = new HashSet<>();
                        List<Object> point = new ArrayList<>();
                        //获取坐标
//                        List<Double> onePoint = FileElseUtil.getObjectToList(redisUtil.hget(RedisName.TARGET_BASE_DATA_ALL + "_" + relationship.getTargetOne(), "position"));
//                        List<Double> twoPoint = FileElseUtil.getObjectToList(redisUtil.hget(RedisName.TARGET_BASE_DATA_ALL + "_" + relationship.getTargetTwo(), "position"));
                        List<Double> onePoint = redisUseService.getViewPosition(relationship.getTargetOne());
                        List<Double> twoPoint = redisUseService.getViewPosition(relationship.getTargetTwo());
                        //判断指向关系生成相应position提供标会使用
                        if (relationship.getPoint().contains("1指向")) {
                            point.add(onePoint);
                            point.add(twoPoint);
                        } else if (relationship.getPoint().contains("2指向")) {
                            point.add(twoPoint);
                            point.add(onePoint);
                        } else {
                            point.add(onePoint);
                            point.add(twoPoint);
                            point.add(onePoint);
                        }
                        poineMap.put("position", point);
                        poineMap.put("targetOne", relationship.getTargetOne());
                        poineMap.put("targetTwo", relationship.getTargetTwo());
                        poineMap.put("color", relationship.getColor());
                        //计算两个点的中心点坐标
                        LngLatUtil.Position position1 = new LngLatUtil.Position(onePoint.get(1), onePoint.get(0));
                        LngLatUtil.Position position2 = new LngLatUtil.Position(twoPoint.get(1), twoPoint.get(0));
                        LinkedList<LngLatUtil.Position> postionList = new LinkedList<>();
                        postionList.add(position1);
                        postionList.add(position2);
                        Map<String, Double> centerPoint = LngLatUtil.getCenterPoint(postionList);
                        poineMap.put("centerPoint", Arrays.asList(centerPoint.get("centerLon"), centerPoint.get("centerLat"), 0));
                        //封装
                        mainMap.put(relationship.getTargetOne() + "&&" + relationship.getTargetTwo(), poineMap);
                        nameSet.add(relationship.getRelationType());
                        setMap.put(relationship.getTargetOne() + "&&" + relationship.getTargetTwo(), nameSet);
                    }
                }
            }
            if (CollectionUtil.isNotEmpty(mainMap)) {
                for (String s : mainMap.keySet()) {
                    Map<String, Object> map = mainMap.get(s);
                    Set<String> set = setMap.get(s);
                    StringBuffer sb = new StringBuffer();
                    int num = set.size();
                    for (String str : set) {
                        if (1 == num) {
                            sb.append(str);
                        } else {
                            sb.append(str + "丨");
                        }
                        num--;
                    }
                    map.put("randomId", snow.nextId() + "");
                    map.put("relation", sb.toString());
                    points.add(map);
                }
            }
            resultMap.put("positions", points);
        } else {
            resultMap.put("positions", ListUtil.empty());
        }
        //字体设置
        FontTable fontTable = redisUseService.getFont("作用范围名称");
        Map<String, Object> font = new HashMap<>();
        font.put("fontName", fontTable.getFontName());
        font.put("fontSize", fontTable.getFontSize());
        font.put("fontColor", fontTable.getFontColor());
        //体系包含目标全部上图
        List<Object> subTarget = new ArrayList<>();
        if (isTarget && CollectionUtil.isNotEmpty(systemsTargetList)) {
            Map<String, Object> map;
            for (String id : systemsTargetList) {
                if (!redisUtil.hasKey(RedisName.TARGET_BASE_DATA_ALL + "_" + id)) {
                    continue;
                }
                map = new HashMap<>();
                map.put("targetId", id);
                map.put("name", redisUtil.hget(RedisName.TARGET_BASE_DATA_ALL + "_" + id, "targetName"));
                redisUseService.getViewData(map, id, true);
                redisUseService.getTypeNameAndIcon(id, 1, map);
                redisUseService.getSystemsRelationRangeValue(sysId, id, map);
                if (StringUtils.isNotBlank(targetId)) {
                    if (id.equals(targetId)) {
                        map.put("principal", true);
                    } else {
                        map.put("principal", false);
                    }
                }
                map.putAll(font);
                subTarget.add(map);
            }
        } else if (CollectionUtil.isNotEmpty(targetIds)) {
            Map<String, Object> map;
            for (String id : targetIds) {
                if (!redisUtil.hasKey(RedisName.TARGET_BASE_DATA_ALL + "_" + id)) {
                    continue;
                }
                map = new HashMap<>();
                map.put("targetId", id);
                map.put("name", redisUtil.hget(RedisName.TARGET_BASE_DATA_ALL + "_" + id, "targetName"));
                redisUseService.getViewData(map, id, true);
                redisUseService.getTypeNameAndIcon(id, 1, map);
                if (StringUtils.isNotBlank(targetId)) {
                    if (id.equals(targetId)) {
                        redisUseService.getSystemsRelationRangeValue(sysId, id, map);
                    } else {
                        map.put("rangeList", ListUtil.empty());
                    }
                } else {
                    redisUseService.getSystemsRelationRangeValue(sysId, id, map);
                }
                if (StringUtils.isNotBlank(targetId)) {
                    if (id.equals(targetId)) {
                        map.put("principal", true);
                    } else {
                        map.put("principal", false);
                    }
                }
                map.putAll(font);
                subTarget.add(map);
            }
        }
//        if (isTarget && redisUtil.hasKey(RedisName.POSTURE_RELATION_LIST + "_" + sysId)) {
//            Map<String, Object> map;
//            Set<Object> set = redisUtil.sGet(RedisName.POSTURE_RELATION_LIST + "_" + sysId);
//            for (Object id : set) {
//                if (redisUtil.hasKey(RedisName.TARGET_BASE_DATA_ALL + "_" + id)) {
//                    if (!redisUtil.hasKey(RedisName.TARGET_BASE_DATA_ALL + "_" + id)) {
//                        continue;
//                    }
//                    map = new HashMap<>();
//                    map.put("targetId", id);
//                    map.put("name", redisUtil.hget(RedisName.TARGET_BASE_DATA_ALL + "_" + id, "targetName"));
//                    redisUseService.getViewData(map, id.toString(), true);
//                    redisUseService.getTypeNameAndIcon(id.toString(), 3, map);
//                    redisUseService.getSystemsRelationRangeValue(sysId, id.toString(), map);
//                    map.put("principal", false);
//                    subTarget.add(map);
//                }
//            }
//        }
        resultMap.put("subTarget", subTarget);
        return ResultUtil.success(resultMap);
    }

    @Override
    public Result preSubTask(String targetId, String userId) throws SQLException {
        com.xinchuang.entity.targetSystem.target.TargetData target = targetMapper.findTargetOnly(targetId);
        if (null != target && target.getDeleteSign() != 0) {
            if (StringUtils.isBlank(target.getTargetClassify())) {
                return ResultUtil.error(ResultEnum.TARGET_TYPE_NOT_NULL);
            }
            String className = TargetUtil.getParamListOrString(target.getTargetClassify());
            QueryWrapper<TargetSubType> wrapper = new QueryWrapper<>();
            wrapper.lambda().eq(TargetSubType::getParentId, className);
            List<TargetSubType> targetSubTypes = targetSubTypeMapper.selectList(wrapper);
            if (CollectionUtil.isNotEmpty(targetSubTypes)) {
                for (int i = 0; i < targetSubTypes.size(); i++) {
                    TargetSubType targetSubType = targetSubTypes.get(i);
                    List<TargetData> subList = new ArrayList<>();
                    for (int j = 0; j < 7; j++) {
                        TargetData targetData = new TargetData();
                        targetData.setKeyType("text");
                        targetData.setRemark("");
                        switch (j) {
                            case 0:
                                targetData.setKey("targetName");
                                targetData.setKeyName("名称");
                                targetData.setKeyValue(targetSubType.getTypeName());
                                break;
                            case 1:
                                targetData.setKey("targetClassify");
                                targetData.setKeyName("类别");
                                targetData.setKeyValue("[\"" + targetSubType.getTypeId() + "\"]");
                                break;
                            case 2:
                                targetData.setKey("position");
                                targetData.setKeyName("经纬度");
                                targetData.setKeyValue("[" + target.getLon() + "," + target.getLat() + "," + target.getHeight() + "]");
                                break;
                            case 3:
                                targetData.setKey("height");
                                targetData.setKeyName("高程");
                                targetData.setKeyValue(target.getHeight() + "");
                                targetData.setRemark("m");
                                break;
                            case 4:
                                targetData.setKey("area");
                                targetData.setKeyName("面积");
                                targetData.setKeyValue("");
                                targetData.setRemark("㎡");
                                break;
                            case 5:
                                targetData.setKey("desicribe");
                                targetData.setKeyName("描述");
                                targetData.setKeyValue("");
                                break;
                            case 6:
                                targetData.setKey("newimageUrl");
                                targetData.setKeyName("图片");
                                targetData.setKeyValue("[]");
                                break;
                        }
                        subList.add(targetData);
                    }
                    //保存子目标
                    String subId = String.valueOf(snow.nextId());
                    TargetSubRelationTable relationTable = new TargetSubRelationTable();
                    relationTable.setTargetId(targetId);
                    relationTable.setSubId(subId);
                    relationTable.setPreType(2);
                    List<TargetSubMsgTable> subMsg = TargetUtil.getSubMsg(subId, subList, userId, 1);
                    targetSubRelationTableService.save(relationTable);
                    targetSubMsgTableService.saveBatch(subMsg);
                }
                return selectTargetSubList(targetId);
            }
            return ResultUtil.error(ResultEnum.TARGET_TYPE_NOT_SUB);
        }
        return ResultUtil.error(ResultEnum.TARGET_EMPTY);
    }

    @Override
    public Result autoRemark(String targetId, String subId, int type, String userId) throws SQLException {
        com.xinchuang.entity.targetSystem.target.TargetData targetData = targetMapper.findTargetOnly(targetId);
        if (null == targetData || targetData.getDeleteSign() == 0) {
            return ResultUtil.error(ResultEnum.TARGET_EMPTY);
        }
        String message = commonMapper.findMessage(type);
        if (StringUtils.isBlank(message)) {
            return ResultUtil.error(ResultEnum.AUTO_REMARK_IS_EMPTY);
        }
        Map<String, Object> resultMap = null;
        if (type == 1) {
            return ResultUtil.success(getTargetMessage(targetId, message));
        } else {
            List<TargetSubMsgTable> list = targetSubMsgTableService.lambdaQuery().eq(TargetSubMsgTable::getSubId, subId).list();
            resultMap = TargetUtil.getSubMsgByMap(list);
        }
        if (CollectionUtil.isEmpty(resultMap)) {
            return ResultUtil.error(ResultEnum.TARGET_MESSAGE_IS_EMPTY);
        }
        for (String s : resultMap.keySet()) {
            if (s.equals("position")) {
                List list = FileElseUtil.getStringTransitionList(resultMap.get(s) + "");
                if (CollectionUtil.isNotEmpty(list)) {
                    message = message.replaceAll("\\{lon}", "东经 " + LngLatUtil.latLng2Dfm(Double.valueOf(list.get(0).toString())));
                    message = message.replaceAll("\\{lat}", "北纬 " + LngLatUtil.latLng2Dfm(Double.valueOf(list.get(1).toString())));
                    message = message.replaceAll("\\{height}", list.get(2) + "");
                    //方位
                    String orientation = targetData.getTargetName() + LngLatUtil.getOrientation(targetData.getLon(), targetData.getLat(), Double.valueOf(list.get(0).toString()), Double.valueOf(list.get(1).toString()));
                    message = message.replaceAll("\\{main-orientation}", orientation);
                }
            } else {
                if (null != resultMap.get(s)) {
                    message = message.replace("{" + s + "}", resultMap.get(s).toString());
                }
            }
        }
        return ResultUtil.success(message);
    }

    @Override
    public boolean juageTargetName(String targetId, String name) {
        String id = targetMapper.selectTargetName(name);
        if (StringUtils.isNotBlank(id) && !targetMapper.selectTargetName(name).equals(targetId)) {
            return true;
        }
        return false;
    }

    @Override
    public String getTargetMessage(String targetId, String message) {
        com.xinchuang.entity.targetSystem.target.TargetData targetData = targetMapper.findTargetOnly(targetId);
        if (ObjectUtil.isNotEmpty(targetData)) {
            try {
                List<String> lose = new ArrayList<>();
                lose.add("position");
                lose.add("country-orientation");
                lose.add("distance-orientation");
                lose.add("sub-message");
                //查询目标的所有参数
                List<TargetMsgTable> list = targetMsgTableService.lambdaQuery().eq(TargetMsgTable::getRedId, targetId).list();
                Map<String, Object> targetAll = TargetUtil.getTargetMsgByMap(list);
                if (ObjectUtil.isNotEmpty(targetAll.get("position"))) {
                    List position = FileElseUtil.getStringTransitionList(targetAll.get("position").toString());
                    if (CollectionUtil.isNotEmpty(position)) {
                        String lon = LngLatUtil.latLng2Dfm(Double.valueOf(position.get(0).toString()));
                        String lat = LngLatUtil.latLng2Dfm(Double.valueOf(position.get(1).toString()));
                        message = message.replaceAll("\\{lon}", "东经 " + lon);
                        message = message.replaceAll("\\{lat}", "北纬 " + lat);
                    }
                }
                if (StringUtils.isNotBlank(targetData.getTargetClassify())) {
                    targetAll.put("targetClassify", redisUseService.getTypeName(targetData.getTargetClassify()));
                }
                Zone zone = null;
                if (ObjectUtil.isNotEmpty(targetAll.get("country"))) {
                    //当前地区方位
                    if (targetAll.get("country").toString().contains("中国台湾")) {
                        zone = zoneMapper.getZoneByName("台湾省");
                    } else {
                        zone = zoneMapper.getZoneByName(targetData.getCountry());
                    }
                    if (ObjectUtil.isNotEmpty(zone)) {
                        String orientation = LngLatUtil.getOrientation(zone.getLng(), zone.getLat(), targetData.getLon(), targetData.getLat());
                        message = message.replaceAll("\\{country-orientation}", orientation);
                    }
                    StringBuffer sb = new StringBuffer();
                    if (targetData.getCountry().equals("中国台湾")) {
                        zone = zoneMapper.getZoneByName("厦门市");
                        double distance = LngLatUtil.getDistance(zone.getLng(), zone.getLat(), targetData.getLon(), targetData.getLat());
                        if (distance > 0) {
                            sb.append("距离我厦门市" + String.format("%.1f", distance) + "千米，");
                        } else {
                            sb.append("距离我厦门市" + String.format("%.1f", distance * 1000) + "米，");
                        }
                        zone = zoneMapper.getZoneByName("北京市");
                        distance = LngLatUtil.getDistance(zone.getLng(), zone.getLat(), targetData.getLon(), targetData.getLat());
                        if (distance > 0) {
                            sb.append("北京市" + String.format("%.1f", distance) + "千米");
                        } else {
                            sb.append("北京市" + String.format("%.1f", distance * 1000) + "米");
                        }
                    } else if (targetData.getCountry().equals("中国")) {
                        zone = zoneMapper.getZoneByName("北京市");
                        double distance = LngLatUtil.getDistance(zone.getLng(), zone.getLat(), targetData.getLon(), targetData.getLat());
                        if (distance > 0) {
                            sb.append("距离我北京市" + String.format("%.1f", distance) + "千米，");
                        } else {
                            sb.append("距离我北京市" + String.format("%.1f", distance * 1000) + "米，");
                        }
                    }
                    message = message.replace("{distance-orientation}", sb.toString());
                }
                for (String s : targetAll.keySet()) {
                    if (lose.contains(s)) {
                        continue;
                    }
                    message = message.replaceAll("\\{" + s + "}", ObjectUtil.isNotEmpty(targetAll.get(s)) ? targetAll.get(s).toString() : "");
                }
            } catch (Exception sqlException) {
                log.error(sqlException.getMessage(), sqlException);
                return "";
            }
            StringBuffer subSB = new StringBuffer();
            StringBuffer subMess = new StringBuffer();
            String yaohai = "";
            //子目标
            try {
                List<String> subData = new ArrayList<>();
                subData.add("targetName");
                subData.add("targetClassify");
                subData.add("area");
                subData.add("crucial");
                subData.add("longth");
                subData.add("breath");
                subData.add("material");
                subData.add("crucial");
                subData.add("position");
                int yaohaiValue = 0;
                List<TargetSubRelationTable> subList = targetSubRelationTableService.lambdaQuery()
                        .eq(TargetSubRelationTable::getTargetId, targetId)
                        .eq(TargetSubRelationTable::getPreType, 1).list();
                if (CollectionUtil.isNotEmpty(subList)) {
                    Map<String, Integer> subMap = new HashMap<>();
                    int count = 0;
                    String subType = "";
                    List<Double> position = null;
                    int sort = 1;
                    for (TargetSubRelationTable targetSubRelationTable : subList) {
                        List<TargetSubMsgTable> subMsgTables = targetSubMsgTableService.lambdaQuery()
                                .eq(TargetSubMsgTable::getSubId, targetSubRelationTable.getSubId())
                                .list();
                        Map<String, Object> map = TargetUtil.getSubMsgByMap(subMsgTables);
                        if (null != map.get("crucial")) {
                            Integer crucial = Integer.valueOf(map.get("crucial").toString());
                            if (crucial > yaohaiValue) {
                                yaohai = map.get("targetName").toString();
                            }
                        }
                        if (ObjectUtil.isNotEmpty(map.get("position"))) {
                            position = FileElseUtil.getStringTransitionList(map.get("position").toString());
                        }
                        //获取子目标类型数量
                        if (ObjectUtil.isNotEmpty(map.get("targetClassify"))) {
                            String classify = TargetUtil.getParamListOrString(map.get("targetClassify").toString());
                            if (null != classify) {
                                count = subMap.get(classify);
                            } else {
                                count = 0;
                            }
                            count += 1;
                            subMap.put(classify, count);
                        }
                        subMess.append(sort + "、" + map.get("targetName") + "：位于");
                        if (CollectionUtil.isNotEmpty(position)) {
                            subMess.append(targetData.getTargetName() + LngLatUtil.getOrientation(targetData.getLon(), targetData.getLat(), position.get(0), position.get(1)) + "，");
                        }
                        subMess.append("长" + map.get("longth") + "，");
                        subMess.append("宽" + map.get("breath") + "，");
                        subMess.append("面积" + map.get("area") + "，");
                        if (CollectionUtil.isNotEmpty(position)) {
                            subMess.append("海拔高" + position.get(2) + "米，");
                            subMess.append("东经 " + LngLatUtil.latLng2Dfm(Double.valueOf(position.get(0).toString())) + "，");
                            subMess.append("北纬 " + LngLatUtil.latLng2Dfm(Double.valueOf(position.get(0).toString())) + "，");
                        } else {
                            subMess.append("海拔高0米，");
                        }
                        subMess.append("材质是" + map.get("material"));
                        subMess.append("；");
                        subMess.append("\n");
                        sort++;
                    }
                    sort = 1;
                    if (CollectionUtil.isNotEmpty(subMap)) {
                        subSB.append("主要子目标有：");
                        for (String s : subMap.keySet()) {
                            subType = redisUseService.getSubTypeName(s);
                            if (StringUtils.isNotBlank(subType)) {
                                subSB.append(subType + subMap.get(s) + "个");
                            }
                            if (sort == subMap.size()) {
                                subSB.append("。");
                            } else {
                                subSB.append("，");
                            }
                            sort++;
                        }
                    } else {
                        subSB.append("。");
                    }
                    subSB.append("\n");
                    subSB.append(subMess.toString());
                } else {
                    subSB.append("该目标暂无子目标信息。");
                }
            } catch (Exception e) {

            }
            //要害部位
            if (StringUtils.isNotBlank(yaohai)) {
                subSB.append(targetData.getTargetName() + "要害子目标为" + yaohai + "。");
            } else {
                subSB.append(targetData.getTargetName() + "暂无要害子目标。");
            }
            message = message.replace("{sub-message}", subSB.toString());
        }
        return message;
    }

    @Override
    public Result getSubList(String targetId) {
        com.xinchuang.entity.targetSystem.target.TargetData only = targetMapper.findTargetOnly(targetId);
        if (ObjectUtil.isNotEmpty(only)) {
            try {
                List<Map<String, Object>> resultList = new ArrayList<>();
                List<String> data = new ArrayList<>();
                data.add("targetName");
                data.add("targetClassify");
                data.add("position");
                //查询子目标列表
                List<TargetSubRelationTable> list = targetSubRelationTableService.lambdaQuery()
                        .eq(TargetSubRelationTable::getTargetId, targetId)
                        .eq(TargetSubRelationTable::getPreType, 1)
                        .list();
                if (CollectionUtil.isNotEmpty(list)) {
                    for (TargetSubRelationTable relationTable : list) {
                        List<TargetSubMsgTable> subMsgTables = targetSubMsgTableService.lambdaQuery()
                                .eq(TargetSubMsgTable::getSubId, relationTable.getSubId())
                                .list();
                        Map<String, Object> map = TargetUtil.getSubMsgByMap(subMsgTables);
                        map.put("subId", relationTable.getSubId());
                        //坐标数据封装
                        SystemPosition position = systemPositionMapper.getPositionById(relationTable.getSubId());
                        if (null != map.get("position")) {
                            map.put("position", FileElseUtil.getStringTransitionList(map.get("position").toString()));
                        }
                        if (null != position) {
                            map.put("viewDistances", FileElseUtil.getStringTransitionList(position.getViewDistances()));
                            double height = FileElseUtil.getStringTransitionDouble(position.getHeight());
                            map.put("height", height == 0 ? null : height);
                        } else {
                            map.put("viewDistances", new ArrayList<>());
                            map.put("height", null);
                        }
                        if (ObjectUtil.isNotEmpty(map.get("targetClassify"))) {
                            String classify = TargetUtil.getParamListOrString(map.get("targetClassify").toString());
                            map.put("targetType", redisUseService.getSubTypeName(classify));
                            String sign = redisUseService.getTypeSign(classify);
                            map.put("icon", this.keyWordSystem.getSERVER_URL() + "/sign/" + sign);
                        } else {
                            map.put("targetType", null);
                            map.put("icon", null);
                        }
                        map.put("zkwcType", 1);
                        resultList.add(map);
                    }
                }
                return ResultUtil.success(resultList);
            } catch (Exception sqlException) {
                log.error(sqlException.getMessage(), sqlException);
            }
        }
        return ResultUtil.success(new ArrayList<>());
    }

    @Override
    public Result getTargetOrSubAllMessage(String targetId, String subId) {
        Map<String, Object> finalMap = new HashMap<>();
        List<Map<String, Object>> resultList = new ArrayList<>();
        Map<String, Object> resutMap = new HashMap<>();
        com.xinchuang.entity.targetSystem.target.TargetData only = targetMapper.findTargetOnly(targetId);
        if (StringUtils.isBlank(subId)) {
            if (ObjectUtil.isNotEmpty(only)) {
                //主目标属性
                List<TargetMsgTable> msgTables = targetMsgTableService.lambdaQuery()
                        .eq(TargetMsgTable::getRedId, targetId)
                        .list();
                for (TargetMsgTable msgTable : msgTables) {
                    resutMap.put(msgTable.getKeyName(), msgTable.getKeyValue() + msgTable.getRemark());
                }
                if (ObjectUtil.isNotEmpty(resutMap.get("类别"))) {
                    resutMap.put("类别", redisUseService.getTypeName(TargetUtil.getParamListOrString(only.getType())));
                }
            }
        } else {
            if (ObjectUtil.isNotEmpty(only)) {
                String subType = null;
                try {
                    //子目标属性
                    List<TargetSubMsgTable> list = targetSubMsgTableService.lambdaQuery().eq(TargetSubMsgTable::getSubId, subId).list();
                    Map<String, Object> dataList = new HashMap<>();
                    for (TargetSubMsgTable targetSubMsgTable : list) {
                        dataList.put(targetSubMsgTable.getKeyName(), targetSubMsgTable.getKeyValue() + targetSubMsgTable.getRemark());
                    }
                    resutMap.putAll(dataList);
                    if (ObjectUtil.isNotEmpty(resutMap.get("类别"))) {
                        TargetSubType type = targetSubTypeMapper.selectById(TargetUtil.getParamListOrString(resutMap.get("类别").toString()));
                        if (ObjectUtil.isNotNull(type)) {
                            subType = type.getTypeName();
                            resutMap.put("类别", type.getTypeName());
                        }
                    }
                } catch (Exception sqlException) {
                    log.error(sqlException.getMessage(), sqlException);
                }
                String[] entity = {"名称", "类别", "高程", "面积", "要害能力指标值"};
                Map<String, Object> map = null;
                for (String s : entity) {
                    for (String s1 : resutMap.keySet()) {
                        if (s.equals(s1)) {
                            map = new HashMap<>();
                            map.put("name", s);
                            map.put("value", resutMap.get(s));
                            map.put("textarea", false);
                            resultList.add(map);
                            break;
                        }
                    }
                }
                List<CommonAttribute> commons = commonMapper.findCommons(2);
                if (CollectionUtil.isNotEmpty(commons)) {
                    for (CommonAttribute common : commons) {
                        if (common.getKeyName().equals("描述") || common.getKeyName().equals("要害能力指标值")) {
                            continue;
                        }
                        for (String s1 : resutMap.keySet()) {
                            if (common.getKeyName().equals(s1)) {
                                map = new HashMap<>();
                                map.put("name", common.getKeyName());
                                map.put("value", resutMap.get(common.getKeyName()));
                                map.put("textarea", false);
                                resultList.add(map);
                                break;
                            }
                        }
                    }
                }
                for (String s1 : resutMap.keySet()) {
                    if (s1.equals("描述")) {
                        map = new HashMap<>();
                        map.put("name", "描述");
                        map.put("value", resutMap.get(s1));
                        map.put("textarea", true);
                        resultList.add(map);
                        break;
                    }
                }
                if (StringUtils.isNotBlank(subType)) {
                    List<SpecialAttribute> specialByTypeId = targetTypeMapper.findSpecialByTypeId(subType);
                    if (CollectionUtil.isNotEmpty(specialByTypeId)) {
                        for (SpecialAttribute specialAttribute : specialByTypeId) {
                            for (String s1 : resutMap.keySet()) {
                                if (specialAttribute.getKeyName().equals(s1)) {
                                    map = new HashMap<>();
                                    map.put("name", specialAttribute.getKeyName());
                                    map.put("value", resutMap.get(specialAttribute.getKeyName()));
                                    map.put("textarea", false);
                                    resultList.add(map);
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
        //前端数据封装
        int radio = 0;
        if (CollectionUtil.isNotEmpty(resutMap) && StringUtils.isBlank(subId)) {
            String[] entity = {"名称", "类别", "国家/地区", "目标等级", "高程", "面积"};
            Map<String, Object> map = null;
            for (String s : entity) {
                for (String s1 : resutMap.keySet()) {
                    if (s.equals(s1)) {
                        map = new HashMap<>();
                        map.put("name", s);
                        if (s.equals("国家/地区") && ObjectUtil.isNotEmpty(resutMap.get(s)) && resutMap.get(s).toString().contains("[")) {
                            List list = FileElseUtil.getStringTransitionList(resutMap.get(s).toString());
                            if (list.size() == 1) {
                                StringBuffer sb = new StringBuffer();
                                if (CollectionUtil.isNotEmpty(list)) {
                                    for (Object o : list) {
                                        Zone zone = zoneMapper.getZoneByAdcode(o.toString());
                                        if (ObjectUtil.isNotEmpty(zone)) {
                                            if (sb.length() == 0) {
                                                sb.append(zone.getName());
                                            } else {
                                                sb.append("/" + zone.getName());
                                            }
                                        }
                                    }
                                }
                                map.put("value", list.get(0));
                            } else {
                                StringBuffer sb = new StringBuffer();
                                if (CollectionUtil.isNotEmpty(list)) {
                                    for (Object o : list) {
                                        Zone zone = zoneMapper.getZoneByAdcode(o.toString());
                                        if (ObjectUtil.isNotEmpty(zone)) {
                                            if (sb.length() == 0) {
                                                sb.append(zone.getName());
                                            } else {
                                                sb.append("/" + zone.getName());
                                            }
                                        }
                                    }
                                }
                                map.put("value", sb.toString());
                            }
                        } else if (s.equals("类别")) {
                            map.put("name", "类型");
                            map.put("value", resutMap.get(s));
                            if (ObjectUtil.isNotEmpty(resutMap.get(s))) {
                                if (resutMap.get(s).toString().contains("雷达站")) {
                                    radio = 1;
                                } else if (resutMap.get(s).toString().contains("导弹阵地")) {
                                    radio = 2;
                                }
                            }
                        } else {
                            map.put("value", resutMap.get(s));
                        }
                        map.put("textarea", false);
                        resultList.add(map);
                        break;
                    }
                }
            }
            List<CommonAttribute> commons = commonMapper.findCommons(1);
            if (CollectionUtil.isNotEmpty(commons)) {
                for (CommonAttribute common : commons) {
                    if (common.getKeyName().equals("描述")) {
                        continue;
                    }
                    for (String s1 : resutMap.keySet()) {
                        if (common.getKeyName().equals(s1)) {
                            map = new HashMap<>();
                            map.put("name", common.getKeyName());
                            map.put("value", resutMap.get(common.getKeyName()));
                            map.put("textarea", false);
                            resultList.add(map);
                            break;
                        }
                    }
                }
            }
            for (String s1 : resutMap.keySet()) {
                if (s1.equals("描述")) {
                    map = new HashMap<>();
                    map.put("name", "描述");
                    map.put("value", resutMap.get(s1));
                    map.put("textarea", true);
                    resultList.add(map);
                    break;
                }
            }
            if (StringUtils.isBlank(subId) && radio > 0) {
                map = new HashMap<>();
                if (radio == 1) {
                    if (ObjectUtil.isNotEmpty(resutMap.get("探测距离(m)"))) {
                        map.put("name", "探测距离(m)");
                        map.put("value", resutMap.get("探测距离(m)"));
                    } else if (ObjectUtil.isNotEmpty(resutMap.get("探测距离"))) {
                        map.put("name", "探测距离(m)");
                        map.put("value", resutMap.get("探测距离"));
                    }
                } else {
                    if (ObjectUtil.isNotEmpty(resutMap.get("防卫距离(m)"))) {
                        map.put("name", "防卫距离(m)");
                        map.put("value", resutMap.get("防卫距离(m)"));
                    } else if (ObjectUtil.isNotEmpty(resutMap.get("防卫距离"))) {
                        map.put("name", "防卫距离(m)");
                        map.put("value", resutMap.get("防卫距离"));
                    }
                }
                map.put("textarea", false);
                resultList.add(map);
            }
            List<SpecialAttribute> specialByTypeId = targetTypeMapper.findSpecialByTypeId(only.getTargetClassify());
            if (CollectionUtil.isNotEmpty(specialByTypeId)) {
                for (SpecialAttribute specialAttribute : specialByTypeId) {
                    for (String s1 : resutMap.keySet()) {
                        if (specialAttribute.getKeyName().equals(s1)) {
                            map = new HashMap<>();
                            map.put("name", specialAttribute.getKeyName());
                            map.put("value", resutMap.get(specialAttribute.getKeyName()));
                            map.put("textarea", false);
                            resultList.add(map);
                            break;
                        }
                    }
                }
            }
        }
//        if (CollectionUtil.isNotEmpty(resutMap)) {
//            List<String> loseList = new ArrayList<>(6);
//            loseList.add("经纬度");
//            loseList.add("标绘信息");
//            loseList.add("图片");
//            loseList.add("名称");
//            loseList.add("类别");
//            if (StringUtils.isBlank(subId)) {
//                loseList.add("国家/地区");
//            }
//            Map<String, Object> map = null;
//            for (int i = 0; i < 3; i++) {
//                map = new HashMap<>();
//                switch (i) {
//                    case 0:
//                        map.put("name", "名称");
//                        map.put("value", resutMap.get("名称"));
//                        map.put("textarea", false);
//                        break;
//                    case 1:
//                        map.put("name", "类型");
//                        map.put("value", resutMap.get("类别"));
//                        map.put("textarea", false);
//                        break;
//                    case 2:
//                        if (StringUtils.isBlank(subId)) {
//                            map.put("name", "国家/地区");
//                            map.put("value", resutMap.get("国家/地区"));
//                            map.put("textarea", false);
//                        }
//                        break;
//                }
//                if (CollectionUtil.isNotEmpty(map)) {
//                    resultList.add(map);
//                }
//            }
//            for (String s : resutMap.keySet()) {
//                if (loseList.contains(s)) {
//                    continue;
//                }
//                map = new HashMap<>();
//                map.put("name", s);
//                map.put("value", resutMap.get(s));
//                if (s.contains("描述")) {
//                    map.put("textarea", true);
//                } else {
//                    map.put("textarea", false);
//                }
//                resultList.add(map);
//            }
//        }
        finalMap.put("message", resultList);
        return ResultUtil.success(finalMap);
    }

    @Override
    public Result getTargetIndex(String targetId) {
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> list = new ArrayList<>();
        List<Double> doubles = new ArrayList<>();
        List<SystemIndex> indexList = systemIndexService.getTargetIndex(targetId);
        double max = 0.0;
        for (SystemIndex systemIndex : indexList) {
            double aDouble = Double.parseDouble(systemIndex.getIndicatorValue());
            doubles.add(aDouble > 100 ? 100 : aDouble);
            if (aDouble > max) {
                max = aDouble;
            }
        }
        Map<String, Object> map;
        for (SystemIndex index : indexList) {
            map = new HashMap<>();
            map.put("name", index.getIndicatorName());
            map.put("max", max);
            list.add(map);
        }
        resultMap.put("dataList", list);
        resultMap.put("valueList", doubles);
        return ResultUtil.success(resultMap);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result resetTargetIndex(String targetId) {
        redisUseService.deleteIndexLevelValue(targetId, "1", null);
        if (redisUseService.isTarget(targetId)) {
            com.xinchuang.entity.targetSystem.target.TargetData targetData = targetMapper.findTargetOnly(targetId);
            if (ObjectUtil.isEmpty(targetData) || targetData.getDeleteSign() == 0) {
                return ResultUtil.error(ResultEnum.TARGET_EMPTY);
            }
            systemIndexService.lambdaUpdate().eq(SystemIndex::getRedId, targetId).remove();
            //构建指标值
            executableStateService.saveOrUpdate(ExecutableState.builder().id(targetId).state(1).build());
            asyncService.createIndexInit(targetData.getTargetName(), targetData.getType(), targetData.getTargetId());
            return ResultUtil.success();
        }
        if (redisUseService.isSub(targetId)) {
            systemIndexService.lambdaUpdate().eq(SystemIndex::getRedId, targetId).remove();
            String subName = redisUtil.hget(RedisName.TARGET_BASE_DATA_ALL + "_" + targetId, "targetName").toString();
            String classify = TargetUtil.getObjectListOrString(redisUtil.hget(RedisName.TARGET_BASE_DATA_ALL + "_" + targetId, "targetClassify"));
            //构建指标值
            executableStateService.saveOrUpdate(ExecutableState.builder().id(targetId).state(1).build());
            asyncService.createIndexInit(subName, classify, targetId);
            return ResultUtil.success();
        }
        return ResultUtil.error(ResultEnum.TARGET_EMPTY);
    }

    @Override
    public Result subPull(JSONObject json) {
        String targetId = json.getString("targetId");
        if (redisUtil.hasKey(RedisName.TARGET_SUB_RELATION_LIST + "_" + targetId)) {
            Set<Object> set = redisUtil.sGet(RedisName.TARGET_SUB_RELATION_LIST + "_" + targetId);
            List<Map<Object, Object>> list = new ArrayList<>();
            for (Object id : set) {
                if (redisUtil.hasKey(RedisName.TARGET_BASE_DATA_ALL + "_" + id)) {
                    Map<Object, Object> map = new HashMap();
                    map.put("value", id);
                    map.put("label", redisUtil.hget(RedisName.TARGET_BASE_DATA_ALL + "_" + id, "targetName"));
                    list.add(map);
                }
            }
            return ResultUtil.success(list);
        }
        return ResultUtil.success(ListUtil.empty());
    }

    @Override
    public Result addSubRelationShip(JSONObject json) {
        String targetId = json.getString("targetId");
        if (StringUtils.isBlank(targetId)) {
            return ResultUtil.error(500, "请选择需要添加关联关系的目标");
        }
        JSONArray relationship = json.getJSONArray("targetRelationship");
        if (CollectionUtil.isNotEmpty(relationship)) {
            for (int i = 0; i < relationship.size(); i++) {
                JSONObject s = relationship.getJSONObject(i);
                TargetRelationship ship = new TargetRelationship();
                if (!"0".equals(s.getString("targetShipId"))) {
                    ship.setTargetShipId(s.getString("targetShipId"));
                }
                String subOne = s.getString("subOne");
                String subTwo = s.getString("subTwo");
                if (StringUtils.isBlank(subOne) || StringUtils.isBlank(subTwo)) {
                    return ResultUtil.error(500, "请选择需要关联的子目标");
                }
                if (subOne.equals(subTwo)) {
                    return ResultUtil.error(500, "关联的子目标不能选择同一个");
                }
                ship.setTargetId(targetId);
                ship.setSubOne(subOne);
                ship.setSubTwo(subTwo);
                ship.setPoint(s.getString("point"));
                ship.setRelationType(s.getString("relationType"));
                targetRelationshipService.saveOrUpdate(ship);
            }
        }
        return ResultUtil.success("目标关系保存成功", null);
    }

    @Override
    public Result deleteRelationShip(JSONObject json) {
        String targetShipId = json.getString("targetShipId");
        targetRelationshipService.removeById(targetShipId);
        return ResultUtil.success("删除成功", null);
    }

    @Override
    public Result selectSubRelationShip(JSONObject json) {
        String targetId = json.getString("targetId");
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("targetRelationship", ListUtil.empty());
        List<TargetRelationship> relationships = targetRelationshipService.lambdaQuery().eq(TargetRelationship::getTargetId, targetId).list();
        if (CollectionUtil.isNotEmpty(relationships)) {
            List<Map<String, Object>> list = new ArrayList<>();
            for (TargetRelationship relationship : relationships) {
                Map<String, Object> map = new HashMap<>();
                map.put("targetShipId", relationship.getTargetShipId());
                map.put("targetId", targetId);
                map.put("subOne", relationship.getSubOne());
                map.put("subTwo", relationship.getSubTwo());
                map.put("point", relationship.getPoint());
                map.put("relationType", relationship.getRelationType());
                list.add(map);
            }
            resultMap.put("targetRelationship", list);
            resultMap.putAll(selectSubRelationShip(targetId));
            return ResultUtil.success(resultMap);
        }
        return ResultUtil.success(resultMap);
    }

    @Override
    public Map<String, Object> selectSubRelationShip(String targetId) {
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("edges", ListUtil.empty());
        resultMap.put("nodes", ListUtil.empty());
        List<TargetRelationship> relationships = targetRelationshipService.findByTargetId(targetId);
        if (CollectionUtil.isNotEmpty(relationships)) {
            ArrayList<JSONObject> parentList = new ArrayList<>();
            List<JSONObject> list = new ArrayList<>();
            Map<String, Set<String>> cMap = new HashMap<>();
            Map<String, String> tMap = new HashMap<>();
            LinkedHashSet lhs = new LinkedHashSet();
            for (TargetRelationship relationship : relationships) {
                if (redisUtil.hasKey(RedisName.TARGET_BASE_DATA_ALL + "_" + relationship.getSubOne())
                        && redisUtil.hasKey(RedisName.TARGET_BASE_DATA_ALL + "_" + relationship.getSubTwo())) {
                    String subOneName = redisUtil.hget(RedisName.TARGET_BASE_DATA_ALL + "_" + relationship.getSubOne(), "targetName").toString();
                    String subTwoName = redisUtil.hget(RedisName.TARGET_BASE_DATA_ALL + "_" + relationship.getSubTwo(), "targetName").toString();

                    JSONObject parent = new JSONObject();
                    parent.put("name", subOneName);
                    JSONObject parentRelation = new JSONObject();
                    parentRelation.put("name", subTwoName);
                    parentList.add(parentRelation);
                    parentList.add(parent);

                    //关系图
                    String one = subOneName + "&&" + subTwoName;
                    String two = subTwoName + "&&" + subOneName;
                    if (null == cMap.get(one)) {
                        if (null == cMap.get(two)) {
                            if ("目标1指向目标2".equals(relationship.getPoint())) {
                                tMap.put(one, "1");
                            } else if ("目标2指向目标1".equals(relationship.getPoint())) {
                                tMap.put(one, "2");
                            } else {
                                tMap.put(one, "3");
                            }
                            Set<String> set = new HashSet<>();
                            set.add(relationship.getRelationType());
                            cMap.put(one, set);
                        } else {
                            Set<String> set = cMap.get(two);
                            set.add(relationship.getRelationType());
                            cMap.put(two, set);
                        }
                    } else {
                        Set<String> set = cMap.get(one);
                        set.add(relationship.getRelationType());
                        cMap.put(one, set);
                    }
                }
            }
            for (String s : tMap.keySet()) {
                JSONObject children = new JSONObject();
                if ("1".equals(tMap.get(s))) {
                    children.put("source", s.split("&&")[0]);//父级名称
                    children.put("target", s.split("&&")[1]);//子级名称
                    Set<String> set = cMap.get(s);
                    StringBuffer sb = new StringBuffer();
                    int num = set.size();
                    for (String str : set) {
                        if (1 == num) {
                            sb.append(str);
                        } else {
                            sb.append(str + "丨");
                        }
                        num--;
                    }
                    children.put("value", sb.toString());//关系
                } else if ("2".equals(tMap.get(s))) {
                    children.put("source", s.split("&&")[1]);//父级名称
                    children.put("target", s.split("&&")[0]);//子级名称
                    Set<String> set = cMap.get(s);
                    StringBuffer sb = new StringBuffer();
                    int num = set.size();
                    for (String str : set) {
                        if (1 == num) {
                            sb.append(str);
                        } else {
                            sb.append(str + "丨");
                        }
                        num--;
                    }
                    children.put("value", sb.toString());//关系
                } else {
                    children.put("source", s.split("&&")[0]);//父级名称
                    children.put("target", s.split("&&")[1]);//子级名称
                    Set<String> set = cMap.get(s);
                    StringBuffer sb = new StringBuffer();
                    int num = set.size();
                    for (String str : set) {
                        if (1 == num) {
                            sb.append(str);
                        } else {
                            sb.append(str + "丨");
                        }
                        num--;
                    }
                    children.put("value", sb.toString());//关系
                    JSONObject childrenRelation = new JSONObject();
                    childrenRelation.put("source", s.split("&&")[1]);//子级名称
                    childrenRelation.put("target", s.split("&&")[0]);//父级名称
                    childrenRelation.put("value", "");//关系
                    list.add(childrenRelation);
                }
                list.add(children);
            }
            lhs.addAll(parentList);
            resultMap.put("edges", list);
            resultMap.put("nodes", lhs);
        }
        return resultMap;
    }

    /**
     * 批量判断参数是否为空
     *
     * @param strs
     * @return
     */
    private boolean judgeStringNotNull(Object... strs) {
        for (Object str : strs) {
            if (null == str) {
                return false;
            }
        }
        return true;
    }

    private void targetRangeType(String targetId, List<TargetMsgTable> targetMsg) {
        //目标作用范围
        String radio = "";
        String rangeType = "";
        for (TargetMsgTable targetMsgTable : targetMsg) {
            if (targetMsgTable.getKeyId().equals("mbRadioValue")) {
                radio = targetMsgTable.getKeyValue();
            } else if (targetMsgTable.getKeyId().equals("mbRadioType")) {
                rangeType = targetMsgTable.getKeyValue();
            }
        }
        if (StringUtils.isNotBlank(radio) && StringUtils.isNotBlank(rangeType)) {
            SystemsRangeType type = systemsRangeTypeMapper.selectOne(new LambdaQueryWrapper<SystemsRangeType>()
                    .eq(SystemsRangeType::getTargetId, targetId).isNull(SystemsRangeType::getSysId)
                    .last("LIMIT 1"));
            if (ObjectUtil.isEmpty(type)) {
                type = new SystemsRangeType();
                type.setTargetId(targetId);
                type.setRadius(FileElseUtil.getObjectToDouble(radio));
                type.setRangeId(rangeType);
                systemsRangeTypeMapper.insert(type);
            } else {
                type.setRadius(FileElseUtil.getObjectToDouble(radio));
                type.setRangeId(rangeType);
                systemsRangeTypeMapper.updateById(type);
            }
            redisUseService.updateTargetRangeValue(targetId, JSON.toJSONString(type));
        } else {
            redisUseService.deleteTargetRangeValue(targetId, false);
        }
    }

    private void subRangeType(String subId, List<TargetSubMsgTable> targetMsg) {
        //目标作用范围
        String radio = "";
        String rangeType = "";
        for (TargetSubMsgTable targetMsgTable : targetMsg) {
            if (targetMsgTable.getKeyId().equals("mbRadioValue")) {
                radio = targetMsgTable.getKeyValue();
            } else if (targetMsgTable.getKeyId().equals("mbRadioType")) {
                rangeType = targetMsgTable.getKeyValue();
            }
        }
        if (StringUtils.isNotBlank(radio) && StringUtils.isNotBlank(rangeType)) {
            SystemsRangeType type = systemsRangeTypeMapper.selectOne(new LambdaQueryWrapper<SystemsRangeType>()
                    .eq(SystemsRangeType::getTargetId, subId).isNull(SystemsRangeType::getSysId)
                    .last("LIMIT 1"));
            if (ObjectUtil.isEmpty(type)) {
                type = new SystemsRangeType();
                type.setTargetId(subId);
                type.setRadius(FileElseUtil.getObjectToDouble(radio));
                type.setRangeId(rangeType);
                systemsRangeTypeMapper.insert(type);
            } else {
                type.setRadius(FileElseUtil.getObjectToDouble(radio));
                type.setRangeId(rangeType);
                systemsRangeTypeMapper.updateById(type);
            }
            redisUseService.updateTargetRangeValue(subId, JSON.toJSONString(type));
        } else {
            redisUseService.deleteTargetRangeValue(subId, false);
        }
    }

    private void buildIndex(String id, String type, String name) {
        //构建指标值
        executableStateService.saveOrUpdate(ExecutableState.builder().id(id).state(1).build());
        asyncService.createIndexInit(name, type, id);
    }

}
